Alex
Alex

Reputation: 631

Strange DrawRectangle and DrawLine

I want to draw several figures on the PictureBox. I expected that the following code will draw a rectangle with it's full size diagonal, but it doesn't. Line do not connected with bottom-right corner of rectangle. I'm really curious what may be wrong?

    private void onPaint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        Pen p = new Pen(System.Drawing.Color.Black, 2);
        g.DrawRectangle(p, 50, 10, 400, 400);
        g.DrawLine(p, 50, 10, 400, 400);
    }

Upvotes: 0

Views: 1990

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39122

Also, if you declare a Rectangle then you can change the values without needing to change the drawing code. Something like:

    private void onPaint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        Rectangle rc = new Rectangle(50, 10, 400, 400);
        using (Pen p = new Pen(System.Drawing.Color.Black, 2))
        {
            g.DrawRectangle(p, rc);
            g.DrawLine(p, rc.Left, rc.Top, rc.Right, rc.Bottom);
        }
    }

Upvotes: 0

Ry-
Ry-

Reputation: 224904

In DrawRectangle, the last two arguments are width and height. In DrawLine, the last two arguments are final x and final y.

So just add the starting x and starting y to the width and height to get your diagonal line:

g.DrawRectangle(p, 50, 10, 400, 400);
g.DrawLine(p, 50, 10, 450, 410);

Upvotes: 2

Related Questions