问题
I am trying to draw some ellipse in the same panel, and the coordinators are determined by mouse click. Here is my code, this code can only draw one circle. The newer circle is always updating the older circle on the panel. So there is always only one circle.
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
x = e.X;
y = e.Y;
panel1.Invalidate();
}
Graphics g;
private void panel1_Paint(object sender, PaintEventArgs e)
{
g = panel1.CreateGraphics();
g.FillEllipse(Brushes.Red, x,y, 10, 10);
}
回答1:
This will let you draw many circles:
List<Point> points = new List<Point>(); // List<T> is wonderful !
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
points.Add(e.Location);
panel1.Invalidate();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
g = e.Graphics; // only ever use this one for persistent graphics!!
foreach( Point pt in points)
g.FillEllipse(Brushes.Red, pt.X, pt.Y, 10, 10);
}
delete them all by
points.Clear();
Delete the last one by
points.Remove(points.Last());
For other sizes store List<Rectangle>
instead. For more complex drawing create a DrawAction
class of your own to hold pens, colors or even rotations and other shapes etc..
来源:https://stackoverflow.com/questions/36924016/how-to-draw-multiple-ellipse-in-the-same-panel