user1501127
user1501127

Reputation: 865

unexpected result drawing circle

I am trying to draw a circle that grows in size by drawing one pixel large radius circle ontop of the old and that way creating a growing circle on the pictureBox.

What i am seeing is a drop shaped figure instead of a circle. The code i use is:

        for (int x = 0; x < 20; x++)
        {
            System.Drawing.Graphics graphics = box.CreateGraphics();
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(xpos-10, ypos-10, x, x);
            graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);

        }

What is it that i am missing?

Upvotes: 0

Views: 63

Answers (3)

esskar
esskar

Reputation: 10940

You draw the circle inside the rectangle, when you only increase the hight and width of the rectangle, you also move the center to the right and the bottom. Also, reuse the graphics for better performance

using (var graphics = box.CreateGraphics())
{

    for (int x = 0; x < 20; x++)
    {
        System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(xpos-10-x/2, ypos-10-x/2, x, x);
        graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);

    }
}

Upvotes: 1

John
John

Reputation: 3702

The rectangle x/y is the upper left corner of the rectangle containing the ellipse. If you draw larger circles, you need to move your bounding rectangle too.

        for (int x = 0; x < 20; x++)
        {
            System.Drawing.Graphics graphics = e.Graphics;
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(xpos - 10 - x / 2, ypos - 10 - x / 2, x, x);
            graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);

        }

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476537

If you want the circle to be iso-centric, you need to set the X and Y of the rectangle to the left as well.

Thus:

Rectangle rectangle = new Rectangle(xpos-10-x/2, ypos-10-y/2, x, x);

On the other hand, you won't see the circle grow. Since the PictureBox only swaps buffers after all drawing is done. What you need is a refresh event and use the time to determine the size of the next circle.

Upvotes: 1

Related Questions