0

I want to write some kind of Paint program and I'm facing problem with dynamic drawing shapes on canvas. I have two approaches

1.I can see the drawing shapes when the button mouse is down and the mouse is moving, but drawing next shape clear the canvas.

private void canvas_MouseMove(object sender, MouseEventArgs e)
        {
            if (!buttonPressed) return;
            int x = Math.Min(xStart, e.X);
            int y = Math.Min(yStart, e.Y);
            int width = Math.Max(xStart, e.X) - Math.Min(xStart, e.X);
            int heigth = Math.Max(yStart, e.Y) - Math.Min(yStart, e.Y);
            rect = new Rectangle(x, y, width, heigth);
            Refresh();
}

private void canvas_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawRectangle(Pens.Red, rect);
        }

2.Second approach gives me possibility of drawing multiple shapes (rectangles), lines, text etc, but the shape is visible when the mouse button is up, not during moving the mouse which is unacceptable...

private void canvas_MouseUp(object sender, MouseEventArgs e)
        {    
              Graphics g = canvas.CreateGraphics();
              g.DrawRectangle(Pens.Red, rect);                   
              g.Dispose();
        }

How can I combine this two approaches that I have Paint drawing effect?

meDarq
  • 141
  • 1
  • 13
  • 2
    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.. – TaW Dec 29 '16 at 22:06
  • 1
    [Draw multiple freehand Polyline or Curve drawing - Adding Undo Feature](https://stackoverflow.com/questions/38296729/draw-multiple-freehand-polyline-or-curve-drawing-adding-undo-feature) – Reza Aghaei Dec 29 '16 at 22:07
  • 2
    Use Method 1. Create a `List` variable to store what should be drawn, and you iterate through that list in your paint event. – LarsTech Dec 29 '16 at 22:07

0 Answers0