Drawing new rectangle while preserving the existing rectangles

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Daniel EXBN
    New Member
    • Mar 2012
    • 7

    Drawing new rectangle while preserving the existing rectangles

    Hi!

    I use this code to draw rectangles while mouse is clicked in Panel.

    The rectangle is drawn in the position of the click.

    For now it works good but each time i click in new location in the Panel, the previous rectangle is deleted.

    This is my code to draw:
    Code:
           private void click_AddLocation(object sender, EventArgs e)
            {
    	.
    	.
    	.
    	.
    
                this.Panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.PaintOnMap);
                Panel1.Refresh();
            }
    
            private void PaintOnMap(object sender, PaintEventArgs e)
            {
                RedPen = new Pen(Color.Red, 7);
                Graphics g = e.Graphics;
                PosXDraw = PosX;
                PosYDraw = PosY;
                Rect = new Rectangle(PosXDraw * 3, PosYDraw * 3, 1, 1);
                g.DrawRectangle(RedPen,Rect);
            }
    Thanks in advance!
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    You didn't post the code for it but I'm assuming that during the "..." portion of your click you're updating PosX and PosY? If that's the case, you're adding a paint event handler that's going to draw the same rectangle every single time.

    Instead, try creating objects when you click and storing them in a list, then drawing them all. You could easily add a private member to your form that was something like..

    Code:
    private List<Point> m_points = new List<Point>();
    Then when you click...
    Code:
    int x = /* however you're currently getting PosX */;
    int y = /* however you're currently getting PosY */;
    m_points.Add(new Point(x, y));
    Finally, only use a single paint event and just draw all the points how you want...

    Code:
    /* in some paint event */
    Graphics g = e.Graphics;
    foreach (Point p in m_points)
    {
      g.DrawRectangle(Pens.Red, p.X, p.Y, 1, 1);
    }
    You'll likely still want to trigger a refresh in your click method so your form updates.

    Comment

    • Daniel EXBN
      New Member
      • Mar 2012
      • 7

      #3
      Thanks! works like a charm

      Comment

      Working...