且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中绘制一个矩形

更新时间: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子表单之间画线 [在面板上捕获图形 [
Abusing PictureBox is a usual mistake. Of course you can draw on an instance of a System.Windows.Forms.PictureBox, but there are no situations when it can be useful. It can be useful to draw in an instance of System.Drawing.Image or an instance of any control class, usually derived from System.Windows.Forms.Control.

As to the PictureBox, 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 of Image, obtain an instance of System.Drawing.Graphics using the static factory method System.Drawing.Graphics.FromImage(Image) and draw using Graphics, please see http://msdn.microsoft.com/en-us/library/system.drawing.graphics.fromimage.aspx[^].

In contrast, you should never create an instance of Graphics if you need to render graphics on screen, using any Control. Instead, you should obtain one from the event arguments parameter passed to the overridden method OnPaint or your event handler of the event Paint, 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