Reputation: 353
I have to draw a rectangle using lines whose co-ordinates and measures are already provided.
In the below code, if I call CloseFigure function. C# assumes the drawing is incomplete and hence it draws an another line diagonally to close the rectangle.
If I use a AddRectangle function, the drawing is complete. No issues with that.
How can I complete a drawing, properly using lines?
private void OnPaint(object sender, PaintEventArgs e)
{
Pen redPen = new Pen(Color.Red, 2);
// Create a graphics path
GraphicsPath path = new GraphicsPath();
// Add two lines, a rectangle and an ellipse
Graphics g = e.Graphics;
path.StartFigure();
path.AddLine(20, 20, 20, 400); // left
path.AddLine(20, 20, 400, 20); //top
path.AddLine(400, 20, 400, 400); // right
path.AddLine(20, 400, 400, 400); // bottom
path.CloseFigure();
//This will close the drawing, by drawing a line between starting and ending point
}
Thanks for your help!!
Upvotes: 1
Views: 1073
Reputation: 239646
You're drawing some of your lines "backwards" - for a connected shape, you always want the end coordinates of one line to be the start coordinates of the next line. So:
path.AddLine(20, 400, 20, 20); // left
path.AddLine(20, 20, 400, 20); //top
path.AddLine(400, 20, 400, 400); // right
path.AddLine(400, 400, 20, 400); // bottom
Upvotes: 1