不会出现绘制填充的椭圆

尝试使用visual studio e在c#中绘制一个pacman开始画点,但我有一些麻烦,我写这个类来制作点。

public class draw : System.Windows.Forms.Control { public draw(int x, int y, int h, int c) { System.Drawing.SolidBrush brush1 = new System.Drawing.SolidBrush(System.Drawing.Color.Yellow); System.Drawing.Graphics formGraphics = this.CreateGraphics(); formGraphics.FillEllipse(brush1, new System.Drawing.Rectangle(x, y, h, c)); brush1.Dispose(); formGraphics.Dispose(); } } 

然后在按下一个按钮的forms,它应该创建一些点,但没有任何反应

 draw d = new draw(100,100,100,100); draw d1 = new draw(200,200,200,200); 

您的代码中有两个错误:

1 – 对表格或控件的绘制是非持久性的; 所有绘图必须在Paint事件中发生或从那里触发。 一个好的解决方案是在那里调用绘图代码并将Paint事件的e.Graphics作为参数传递。

2 – 你使用CreateGraphics并试着用它绘画。 一旦你最小化窗口并恢复它,结果就会消失。 但事实上,首先没有任何表现。 为什么? 好吧,你的绘制blob是一个内部类 ,这里的关键字不是表单而是指绘制类 。 因此,您为一个不可见的控件创建一个图形(没有大小,并且不是表单的一部分),当然,没有任何反应..

如果你想要绘图项目,他们应该

  • 存储它们的大小,位置,状态等(在它们的构造函数中)和

  • 有一个绘图方法,你可以从外面调用,并获得一个Graphics对象,然后他们自己绘制..

  • 他们也应该有一个更好的名字,如DotPacDot等。

这是一个最小版本:

 // a list of all PacDots: public List theDots = new List(); public class PacDot : System.Windows.Forms.Control { public PacDot(int x, int y, int w, int h) { Left = x; Top = y; Width = w; Height = h; } public void Draw(Graphics G) { G.FillEllipse(Brushes.Brown, new System.Drawing.Rectangle(Left, Top, Width, Height)); } } private void Form1_Paint(object sender, PaintEventArgs e) { foreach (PacDot dot in theDots) dot.Draw(e.Graphics); } // a test button: private void button1_Click(object sender, EventArgs e) { theDots.Add(new PacDot(30, 10, 5, 5)); theDots.Add(new PacDot(30, 15, 5, 5)); theDots.Add(new PacDot(15, 10, 5, 5)); this.Invalidate(); } 

PS:由于你的绘图类确实是一个Control descedent,你也可以使用form1.Controls.Add(..);将它们添加到Form中。 但他们仍然需要进行油漆活动,他们自己画画。