绘制具有中心点和大小的正方形

时间:2014-06-25 12:57:30

标签: c# vb.net

实施例: 我想绘制一个中心点(10,10)和边缘20的正方形。

如何使用Graphics.DrawRectangle?

3 个答案:

答案 0 :(得分:1)

Graphics.DrawRectangle没有重载将中心点作为参数并在其周围绘制一个矩形。看到这个

我认为您可以创建自己的功能,如下所示:

public void DrawRectangle(Pen pen, int xCenter, int yCenter, int width, int height)
{
    //Find the x-coordinate of the upper-left corner of the rectangle to draw.
    int x = xCenter - width / 2;

    //Find y-coordinate of the upper-left corner of the rectangle to draw. 
    int y = yCenter - height / 2;

    Graphics.DrawRectangle(pen, x, y, width, height);
}

答案 1 :(得分:0)

您有两种选择:

1 - 只需移动图纸即可。如果要绘制一个20x20像素,中心位于10,10,则将其绘制为0,0(中心 - 大小/ 2)

2 - 使用TranslateTransform函数将Graphics原点替换为-Size / 2

如果使用第二种方法,请记得在绘图后重置变换,但我建议使用第一个选项。

答案 2 :(得分:0)

您可以创建扩展方法:

public static class Utilities{
    public static void DrawSquare(this Graphics g, Point center, int edgeSize, Pen pen){
        int halfEdge = edgeSize/2;
        Rectangle square = new Rectangle(center.X - halfEdge, center.Y - halfEdge, edgeSize, edgeSize);
        g.DrawRectangle(pen, square);
    }
}

然后使用它:

e.Graphics.DrawSquare(new Point(10, 10), 20, new Pen(Brushes.Blue));
相关问题