奇怪的DrawRectangle和DrawLine

时间:2013-06-16 14:57:07

标签: c# winforms graphics drawing

我想在PictureBox上绘制几个数字。我希望下面的代码将绘制一个矩形与它的全尺寸对角线,但事实并非如此。线与矩形的右下角没有连接。我真的好奇可能出错了什么?

    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);
    }

2 个答案:

答案 0 :(得分:2)

DrawRectangle中,最后两个参数是宽度和高度。在DrawLine中,最后两个参数是final x和final y。

所以只需将起始x和起始y添加到宽度和高度以获得对角线:

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

答案 1 :(得分:0)

此外,如果声明一个Rectangle,则可以更改值而无需更改绘图代码。类似的东西:

    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);
        }
    }