C# 将位图加载到 PictureBox - 速度慢并且阻塞 UI ..有其他选择吗?
我正在将 640x480 位图一个接一个地加载到图片框中。当我这样做时,我的用户界面被阻止。例如,如果我在文本框中输入内容,而该文本框与图片框的窗体相同,则我将无法立即看到按下的键,因为位图加载使 UI 非常慢。 人们会如何处理呢?有什么办法解决吗? 任何示例代码都会很棒。
谢谢
I am loading 640x480 Bitmaps into a picture box one after the other. When I do that my UI gets blocked. For example, if I was typing something in a text box which is on the same form where my picture box is, I would not be able to see the key that pressed right away, because the bitmap loading makes the UI very slow ..
How would one handle that ? is there any way around it ?
Any sample code would be great.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Picturebox
实际上是一个相当“重”的控件。它可能不适合在这里使用。您可能会考虑使用更简单的容器控件,或者在表单本身的表面上进行绘图。如果您想在这里考虑 BackgroundWorker 或任何其他线程技术,请记住绘图本身必须发生在 UI 线程上;没有办法解决这个问题。
如果从磁盘加载图像是延迟的根源,您可能会考虑将图像加载到另一个线程上的内存位图中,然后以某种方式发出信号以指示已准备好绘制新项目。然后,您将使绘图表面无效,并根据需要添加新项目。
还;如果您要对图像进行任何缩放,那么在后台线程中执行此操作是合适的 - 这样,绘图代码本身只需要绘制一个未缩放的矩形;使用 GDI+ DrawUnscaled 功能将位图复制到完全相同大小的区域实际上相当快。
为了了解更具体的内容,例如实际代码,我想查看您现在如何执行此操作的代码。我什至不确定您是否首先“绘制”图像,而不是简单地设置
Picture
/Image
属性。A
Picturebox
is actually a fairly 'heavy' control in what it provides; it may not be the appropriate thing to use here. You might consider a much simpler container control, or drawing on the surface of the form itself.If you want to consider
BackgroundWorker
or any other threaded technique here, keep in mind that the drawing itself must happen on the UI thread; there's no way around that.If the loading of the images from disk is the source of the latency, you might consider loading the images into an in-memory bitmap on another thread, then signaling somehow to indicate that a new item is ready to be drawn. You would then invalidate the drawing surface, and add the new item as appropriate.
Also; if you are doing any scaling to the images, doing this in the background thread would be appropriate - that way, the drawing code itself only needs to draw an unscaled rect; Using the GDI+ DrawUnscaled functionality to copy a bitmap to an area of the exact same size is actually quite fast.
To get into anything more specific, like actual code, I would want to see code for how you are doing it now. I'm not even sure you are 'drawing' the images in the first place, rather than simply setting
Picture
/Image
properties.使用后台工作程序,这样 gui 就不会被冻结(异步调用图像显示)。
http://www.dreamincode.net/ forums/topic/112547-using-the-backgroundworker-in-c%23/
你的第二个请求有点棘手,我想简短的答案是不要依赖 gdi+,如果这就是你正在做的事情,因为众所周知,它的速度很慢。到底如何将图像加载到图像框中?
Use background worker so the gui is not freezed (async invoke the image display).
http://www.dreamincode.net/forums/topic/112547-using-the-backgroundworker-in-c%23/
Your second request is a bit more tricky, I guess short answer would be not to rely on gdi+ if that's what you are doing be cause it's known to be slow. How exactly do you load the image into the imagebox?