更新时间:2023-02-02 17:27:56
滥用PictureBox
是常见的错误.当然,您可以使用System.Windows.Forms.PictureBox
的实例,但是在任何情况下它都是有用的.绘制System.Drawing.Image
的实例或任何控件类的实例(通常是从System.Windows.Forms.Control
派生的)很有用.
关于PictureBox
,它的设计使显示图片非常简单,一次显示一张完整的静态图片.尝试做任何动态,交互或动画的工作都是在浪费额外的资源和开发时间.它没有提供任何其他功能,只有麻烦.甚至您的简单示例也将是滥用.您可以做到,但您永远都不需要.
不用担心,我会解释该怎么做.
若要绘制Image
的实例,请使用静态工厂方法System.Drawing.Graphics.FromImage(Image)
获取System.Drawing.Graphics
的实例,并使用Graphics
进行绘制,请参见 ^ ].
相反,如果需要使用任何Control
在屏幕上渲染图形,则永远不要创建Graphics
的实例.相反,您应该从传递给重写的方法OnPaint
的事件参数参数中获取一个,或者从事件Paint
的事件处理程序中获取一个,请参见:
http://msdn.microsoft.com/en-us/library/system. windows.forms.control.aspx [ ^ ].
请在我过去的解决方案中找到有关渲染屏幕图形的更多详细信息:
如何从旧图纸中清除面板 [ ^ ],
Paint是一种哪种好玩的方法? (DataGridViewImageCell.Paint(...)) [在mdi子表单之间画线 [在面板上捕获图形 [
AbusingPictureBox
is a usual mistake. Of course you can draw on an instance of aSystem.Windows.Forms.PictureBox
, but there are no situations when it can be useful. It can be useful to draw in an instance ofSystem.Drawing.Image
or an instance of any control class, usually derived fromSystem.Windows.Forms.Control
.
As to thePictureBox
, it is designed to make it very simple to present pictures, one whole static picture at a time. An attempt to do anything dynamic, interactive or animated is just waste of extra resources and development time. It does not present any additional feature, only the hassles. Even your simple example would be an abuse. You can do it, but you never need it.
Not to worry, I''ll explain what to do instead.
To draw on the instance ofImage
, obtain an instance ofSystem.Drawing.Graphics
using the static factory methodSystem.Drawing.Graphics.FromImage(Image)
and draw usingGraphics
, please see http://msdn.microsoft.com/en-us/library/system.drawing.graphics.fromimage.aspx[^].
In contrast, you should never create an instance ofGraphics
if you need to render graphics on screen, using anyControl
. Instead, you should obtain one from the event arguments parameter passed to the overridden methodOnPaint
or your event handler of the eventPaint
, please see:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.aspx[^].
Please find further detail on rendering on-screen graphics in my past solutions:
How do I clear a panel from old drawing[^],
What kind of playful method is Paint? (DataGridViewImageCell.Paint(...))[^],
Drawing Lines between mdi child forms[^],
capture the drawing on a panel[^].—SA