How to Draw Shapes in Winforms

How to draw shapes in WinForms

I looked for sample code that was both simple and worked and did not find anything. You do not need offscreen bitmaps or CreateGraphics for this, but you will need to handle tracking the mouse position, drawing to the screen, and adding drawn shapes to a list of shapes as Eric suggests. To handle interactive drawing you need to store the mouse state, initial click position, and current rectangle in your form handler:

bool mouseDown;
Point clickPos;
Rectangle rect;

Then when the user clicks, remember the initial position:

private void MouseDown(object sender, MouseEventArgs e)
{
mouseDown = true;
clickPos = e.Location;
rect = new Rectangle(clickPos, new Size(0, 0));
}

While the user drags with the mouse down, create a rectangle encompassing the start and current location:

private void MouseMove(object sender, MouseEventArgs e)
{
if (mouseDown)
{
this.Invalidate(rect);
if (e.Location.X > clickPos.X && e.Location.Y > clickPos.Y)
{
rect = new Rectangle(clickPos.X, clickPos.Y, e.Location.X - clickPos.X, e.Location.Y - clickPos.Y);
}
else if (e.Location.X > clickPos.X && e.Location.Y < clickPos.Y)
{
rect = new Rectangle(clickPos.X, e.Location.Y, e.Location.X - clickPos.X, clickPos.Y - e.Location.Y);
}
else if (e.Location.X < clickPos.X && e.Location.Y < clickPos.Y)
{
rect = new Rectangle(e.Location.X, e.Location.Y, clickPos.X - e.Location.X, clickPos.Y - e.Location.Y);
}
else if (e.Location.X < clickPos.X && e.Location.Y > clickPos.Y)
{
rect = new Rectangle(e.Location.X, clickPos.Y, clickPos.X - e.Location.X, e.Location.Y - clickPos.Y);
}

this.Invalidate(rect);
}
}

When the user releases the mouse, stop drawing:

private void MouseUp(object sender, MouseEventArgs e)
{
mouseDown = false;
}

The #1 most important rule in Windows Forms is: only draw to the screen in the Paint event. Never never draw in the MouseMoved event:

private void Paint(object sender, PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.DarkGray, rect);
}

Once you get this working, create a form List<Rectangle> and add the current rectangle in the MouseUp event and draw all rectangles in the Paint event. You might also want to clip your drawing to the panel or window you are drawing in. You can also do some optimizations in MouseMoved to only invalidate the changed screen region, not both the old and new rectangles.

Draw Shape in Windows Form Application

You can use the Rectangle class along with the Matrix class to create a rectangle and then rotate it by your orientation like so:

Graphics g = new Graphics()
Rectangle car = new Rectangle(200, 200, 100, 50)
Matrix m = new Matrix()
m.RotateAt(orientation, new PointF(car.Left + (car.Width / 2), car.Top + (car.Height / 2)));
g.Transform = m
g.FillRectangle(Pens.Red, car)


Related Topics



Leave a reply



Submit