使用Graphics.DrawLine()圈出

时间:2019-02-15 02:34:30

标签: c#

我正在尝试使用graphics.DrawLine()属性并使用BRESENHAM'S CIRCLE ALGORITHM来画一个圆,但是我做不到。这是制作圆圈的方法

Pen pen = new Pen(Color.Red, 2);
Graphics graphics = this.Shape_PictureBox.CreateGraphics();
int radius = 40;
int x = 0, y = radius;
int xc = 50, yc = 50;
int d = 3 - 2 * radius;
    // graphics.DrawLine(pen, xc, yc, x, y);
    while (y >= x)
    {
        x++;
        if (d > 0)
        {
            y--;
            d = d + 4 * (x - y) + 10;
        }
        else
        {
            d = d + 4 * x + 6;
        }
        //drawCircle(xc, yc, x, y);
        graphics.DrawLine(pen, xc, yc, x, y);
    }

1 个答案:

答案 0 :(得分:1)

好吧,如前所述,您的算法实现中似乎有一个错误-但我想您首先要问的是,为什么Shape_PictureBox中什么都不可见?您应该创建一个可绘制的位图缓冲区(将其视为画布),然后将其分配给Shape_PictureBox.Image属性。

重要:请确保在Form_Shown而非Form_Load事件中执行此操作!

private void Child2_Shown(object sender, EventArgs e)
{
    Pen pen = new Pen(Color.Red, 2);
    Bitmap canvas = new Bitmap(Shape_PictureBox.Width, Shape_PictureBox.Height);
    Graphics graphics = Graphics.FromImage(canvas);

    int radius = 40;
    int x = 0;
    int y = radius;
    int xc = 50; 
    int yc = 50;
    int d = 3 - 2 * radius; 

    graphics.DrawLine(pen, xc, yc, x, y);

    while (y >= x)
    {
        x++;
        if (d > 0)
        {
            y--;
            d = d + 4 * (x - y) + 10;
        }
        else
        {
            d = d + 4 * x + 6;
        }

        // drawCircle(xc, yc, x, y); 
        graphics.DrawLine(pen, xc, yc, x, y); 
    }

    Shape_PictureBox.Image = canvas;
}

当前,它看起来像这样:

Not quite a circle

您需要修改Bresenham's Circle算法的实现:)