Sunday 21 May 2023

Draw Circle in C#

 Here's an example program in C# that uses the `System.Drawing` namespace to draw a circle on a Windows Form:


// Mohit Kumar Tyagi

using System;

using System.Drawing;

using System.Windows.Forms;


public class CircleDrawingForm : Form

{

    public CircleDrawingForm()

    {

        // Set the form size and title

        Size = new Size(400, 400);

        Text = "Circle Drawing Example";

    }


    protected override void OnPaint(PaintEventArgs e)

    {

        base.OnPaint(e);


        // Create a Graphics object from the Form's CreateGraphics() method

        Graphics g = e.Graphics;


        // Set the circle color and thickness

        Pen pen = new Pen(Color.Red, 2);


        // Define the circle's center point and radius

        int centerX = 200;

        int centerY = 200;

        int radius = 100;


        // Calculate the top-left corner of the bounding rectangle

        int x = centerX - radius;

        int y = centerY - radius;


        // Draw the circle

        g.DrawEllipse(pen, x, y, radius * 2, radius * 2);


        // Dispose of the pen and graphics objects

        pen.Dispose();

        g.Dispose();

    }


    public static void Main()

    {

        // Create an instance of the CircleDrawingForm class

        Application.Run(new CircleDrawingForm());

    }

}


To run this program, create a new Windows Forms Application project in Visual Studio or any other C# IDE, and replace the default code with the code above. When you run the program, it will display a window with a circle drawn at the center (200, 200) with a radius of 100 pixels.


In this example, the `OnPaint` method is overridden to handle the drawing of the circle. The `Pen` class is used to define the color and thickness of the circle's outline. The `DrawEllipse` method of the `Graphics` class is used to draw the circle by specifying the top-left corner of the bounding rectangle and the width and height of the rectangle.

No comments:

Post a Comment

Draw Circle in C#

 Here's an example program in C# that uses the `System.Drawing` namespace to draw a circle on a Windows Form: // Mohit Kumar Tyagi using...