我有一个绘制椭圆的函数。我想通过更改表单大小来绘制新椭圆时,通过将其颜色更改为与背景相同的颜色来使先前绘制的椭圆不可见。
这是我在课堂上的功能:
class ClassClock
{
public static void drawClock(Point m, int s, Form frm, Color myColor)
{
Graphics paper = frm.CreateGraphics();
Pen myPen = new Pen(myColor);
int w = frm.ClientSize.Width;
int h = frm.ClientSize.Height;
m = new Point(w / 2, h / 2);
s = Math.Min(w, h) / 2;
paper.DrawEllipse(myPen, m.X - s, m.Y - s, s * 2, s * 2);
}
}
这是我的计时器:
private void timer1_Tick(object sender, EventArgs e)
{
ClassClock.drawClock(m, s, this, this.BackColor);
ClassClock.drawClock(m, s, this, Color.Black);
}
有人可以帮我找到解决方案吗?
您不应该这样使用CreateGraphics
。相反,请覆盖表单的OnPaint
方法并使用该方法进行所有绘制。
Windows使用即时模式图形系统。这意味着,绘制椭圆后,椭圆就消失了,只保留当前屏幕上的像素。如果将窗口最小化或在其上拖动另一个窗口,则椭圆将消失并且必须重新粉刷。这就是OnPaint
方法的目的。
这是一种简单的表单,当单击按钮时,它会更改圆圈的颜色。要运行此代码,您将需要在表单中添加一个按钮并将其命名为btnChangeColor。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Property to hold the current color. This could be a private field also.
public Color CurrentColor { get; set; } = Color.Red;
//Used to generate a random number when the button is clicked.
private Random rnd = new Random();
//All painting of the form should be in this method.
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
//Use the graphics event provided to you in PaintEventArgs
Graphics paper = e.Graphics;
int w = this.ClientSize.Width;
int h = this.ClientSize.Height;
Point m = new Point(w / 2, h / 2);
int s = Math.Min(w, h) / 2;
//It is important to dispose of any pens you create
using (Pen myPen = new Pen(CurrentColor))
{
paper.DrawEllipse(myPen, m.X - s, m.Y - s, s * 2, s * 2);
}
}
//When the button is clicked, the `CurrentColor` property is set to a random
//color and the form is refreshed to get it to repaint itself.
private void btnChangeColor_Click(object sender, EventArgs e)
{
//Change the current color
CurrentColor = Color.FromArgb(255, rnd.Next(0, 256), rnd.Next(0, 256), rnd.Next(0, 256));
//Refresh the form so it repaints itself
this.Refresh();
}
}