0

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);
        }
halfer
  • 19,824
  • 17
  • 99
  • 186
perryfanfan
  • 161
  • 3
  • 10

1 Answers1

0

Winforms graphics basic rule #1 : Never use control.CreateGraphics! Never try to cache a Graphics object! Either draw into a Bitmap bmp using a Graphics g = Graphics.FromImage(bmp) or in the Paint event of a control, using the e.Graphics parameter..

You can test the persistance of your graphics by doing a Minimize/Maximize sequence..

The correct way is to keep a list of things to draw and whenever that list changes Invalidate the control you draw on. All drawing should be in the Paint event, using e.Graphics there!

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..

TaW
  • 53,122
  • 8
  • 69
  • 111