简体   繁体   中英

Circle using Graphics.DrawLine()

I'm trying to make a circle using graphics.DrawLine() property and using BRESENHAM'S CIRCLE ALGORITHM but I'm not able to make it. Here is the method for making the circle

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

Well, there appears to be a bug in your algorithm implementation, as posted - but I suppose you're first and foremost asking as to why nothing is visible in the Shape_PictureBox ? You should create a Bitmap buffer (think of it as a canvas) to draw to, and then assign it to the Shape_PictureBox.Image property.

IMPORTANT : Make sure to do this in the Form_Shown , not Form_Load event!

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

Currently, it looks like this:

不太圆

You'll need to revise your implementation of Bresenham's Circle algorithm :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM