[英]Drawing graphics when creating a new object
I played with some custom Controls created by me and I wanted to draw some Graphics for them. 我玩了一些由我创建的自定义控件,我想为其绘制一些图形。
I achieved everything I wanted but I have a question because something seems strange to me. 我实现了想要的一切,但是我有一个问题,因为我觉得有些奇怪。 I tried for example to make a new control like this:
例如,我尝试制作一个像这样的新控件:
public class Square : Control
{
public Square(Point location)
{
this.Size = new Size(100, 100);
this.Location = location;
Draw();
}
public void Draw()
{
Graphics g = this.CreateGraphics();
g.DrawRectangle(Pens.Black, 5, 5, 20, 20);
}
}
This doesn't draw anything, but, if I call the "Draw" method from another action like a button press on the form it works. 这不会绘制任何内容,但是,如果我从另一个操作(如在窗体上按下按钮)调用“ Draw”方法,它将起作用。 It also works if I override the OnPaint method of my control and call the "Draw" method here.
如果我重写控件的OnPaint方法并在此处调用“ Draw”方法,它也将起作用。 (I know that I should make all the drawing in the Paint/OnPaint but I did this just to try other things)
(我知道我应该在“ Paint / OnPaint”中绘制所有图形,但是我这样做只是为了尝试其他事情)
What's the difference ? 有什么不同 ? Why can't I just call my "Draw" method anywhere I want?
为什么我不能只在需要的地方调用我的“绘图”方法?
When you call Draw()
method in constructor, the control has not yet been added to the parent, is just an object in memory, so the call has no effect. 当您在构造函数中调用
Draw()
方法时,该控件尚未添加到父级中,只是内存中的一个对象,因此该调用无效。
If you make the call as you say in the OnPaint()
method, then is drawed since this method is called whenever render the control is needed. 如果您按
OnPaint()
方法中的说明进行调用,则会绘制该控件,因为只要需要渲染控件,就会调用此方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.