user8369850
user8369850

Reputation:

Make circle in C# with only pen tool, without using ellipse method

The code i have made is hard coded and i want it to convert it into circle any snippet i can add or something

The code is in C sharp, The output is like the rectangle which i have to convert it into a circle

        private void pictureBox1_Click(object sender, EventArgs e)
        {
        int length = 100;
        int flag = 0;
        int flag2 = 0;
        int flag3 = 0;

        Pen p = new Pen(Color.Red, 4);
        Graphics g = pictureBox1.CreateGraphics();
        Brush redBrush = new SolidBrush(Color.Red);
        for (int i = 0; i < 20; i++)
        {
                if(i==0 || i<10)
                {
                    g.DrawLine(p, 622 - 10 * i, 229+10*i, 623 - 10 * i, 229+10*i);
                }
                if(i==10)
                {
                    flag = 1;
                }
                if(flag==1)
                {
                    g.DrawLine(p, 622 - 10 * i, 419 - 10 * i, 623 - 10 * i, 419-10*i);
                    flag2 = 1;
                }
                if(flag2 == 1)
                {
                    g.DrawLine(p, 622 - 10 * i, 29+10*i, 623 - 10 * i, 29+10*i);
                    flag3 = 1;
                }
                if (flag3 == 1)
                {
                    g.DrawLine(p, 432 + 10 * i, 29+10*i, 433 + 10 * i, 29 + 10 *i);
                }

        }

Upvotes: 0

Views: 103

Answers (2)

CooncilWorker
CooncilWorker

Reputation: 415

You can do this

void DrawCircle(Graphics g, Pen p, Point centre, double radius=20, int sides = 360)
{
    var angle = 2 * Math.PI / sides;
    for (int i = 0; i < sides; i++)
    {
        Point from = new Point((int)(radius * Math.Sin(i * angle) + centre.X), (int)(radius * Math.Cos(i * angle) + centre.Y));
        Point to = new Point((int)(radius * Math.Sin((i+1) * angle) + centre.X), (int)(radius * Math.Cos((i+1) * angle) + centre.Y));
        g.DrawLine(p, from, to);
    }
}

and to use

DrawCircle(g, p, new Point(100, 100), 50, 8); // 8 sides, an octagon

Increase the number of sides to make it more accurate.

Alternatively,

g.DrawEllipse(p, (float)(centre.X-radius), (float)(centre.Y-radius), (float)radius*2, (float)radius*2);

Upvotes: 0

beyond
beyond

Reputation: 514

There is a built-in function for this. Use g.DrawEllipse() instead.

Upvotes: 1

Related Questions