Windows forms нарисовать круг c

Удобнее всего сделать повторно используемый пользовательский контрол:

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

public sealed class CircleControl : Control
{
    public CircleControl()
    {
        Height = Width = 100;
        SetStyle(ControlStyles.ResizeRedraw | ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        var grfx = e.Graphics;
        grfx.SmoothingMode = SmoothingMode.AntiAlias;
        grfx.DrawEllipse(new Pen(Color), 0, 0, Width-1, Height-1);
        //grfx.FillEllipse(new SolidBrush(color), 0, 0, Width - 1, Height - 1); // рисует закрашенный круг
    }

    private Color color = Color.Black;

    public Color Color
    {
        get
        {
            return color;
        }
        set
        {
            color = value;
            Invalidate();
        }
    }
}

Через свойство Color можно задавать цвет окружности. При смене цвета окружность будет перерисована.

Вы можете рисовать в методе OnPaint разными способами:
DrawEllipse — окружность.
FillEllipse — закрашенный круг.

Добавить контрол на форму можно через дизайнер или в конструкторе:

var сircleControl = new CircleControl();
сircleControl.Color = Color.Red; // меняем цвет окружности
Controls.Add(сircleControl);

Обновление

По умолчанию форма контрола будет прямоугольная и при размещении над другими контролами будут видны края. Чтобы избежать этого эффекта нужно добавить следующий код:

protected override void OnResize(EventArgs e)
{
    base.OnResize(e);

    var rect = ClientRectangle;
    rect.Inflate(-2, -2);
    var path = new GraphicsPath();
    path.AddEllipse(rect);
    Region = new Region(path);
}

  1. Use the Drawing.Ellipse() Method to Draw Circles in C#
  2. Use the FillEllipse() Method to Fill Circles in C#

Draw Circles in C#

In this article, we will be looking at how we can draw a circle in C#.

Use the Drawing.Ellipse() Method to Draw Circles in C#

System.Drawing doesn’t have an explicit circle draw. We can use the Drawing.Ellipse() method, which provides the same functionality or create a new FORM with Windows.FORMS(.NET FRAMEWORK) to allow us to experiment with interfaces.

Draw Circles in C# Using .NET Framework

Ensure that the Paint method is called when you have booted into a FORM. Double click on the form, and the properties will open up.

change properties in .NET Framwork

Switch over to the EVENTS section.

In Events section, double click Paint to produce the function

Inside the EVENTS section now, scroll down till you find the PAINT and double click on it to produce the PAINT function.

Paint function

Now, we create our ELLIPSE using the System.Drawing and then choose the Ellipse option.

e.Graphics.DrawEllipse(new Pen(System.Drawing.Color.Red), new Rectangle(10, 10, 50, 50));

We have chosen a new PEN in the parameters with the color red. The next parameter tends to draw the RECTANGLE encapsulating the circle.

Think of it like the size of the circle, with the first two parameters denoting the origin points ( x and y ) and the last two parameters being the size of the x-axis and the y-axis.

Output:

Draw Circles in C

Use the FillEllipse() Method to Fill Circles in C#

To fill the circle on the above output, we will use the FILLELLIPSE() function.

 e.Graphics.FillEllipse(Brushes.Red, 10, 10, 50, 50);

We defined the same points for the FillEllipse() function as we did for the Drawing.Ellipse() to ensure that the correct area is filled. We have chosen the Brushes.Red brush for it as the first parameter.

Output:

Use the FillEllipse() Method to Fill Circles in C

Full Code Snippet:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.DrawEllipse(new Pen(System.Drawing.Color.Red), new Rectangle(10, 10, 50, 50));

            e.Graphics.FillEllipse(Brushes.Red, 10, 10, 50, 50);
        }

        private void Form1_MouseHover(object sender, EventArgs e)
        {

        }
    }
}

That is how you draw a circle in C#. We hope you learned this well and can modify it as per your needs.

Sumen

241 / 243 / 27

Регистрация: 30.01.2014

Сообщений: 1,145

Записей в блоге: 2

1

Рисование кругов

23.07.2016, 17:33. Показов 33028. Ответов 7

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Задача:
нарисовать несколько кругов (закрашенных окружностей) с центрами в заданных точках, красного цвета, полупрозрачных, диаметр взять из combobox.
Что сделал:
объявил класс:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Krug
        {
            int Daln;
            int x;
            int y;
            public void DrawKrug(object sender, PaintEventArgs e)
            {
                {
                    Graphics g = e.Graphics;
                    Pen pen = new Pen(Color.Red);
                    g.DrawEllipse(pen, x, y, D, D);
                }
            }
                   }

Вставил бокс с передаваемым значением D:

C#
1
2
3
4
5
private void Diam1SelectedIndexChanged(object sender, EventArgs e)
        {
            int D = Convert.ToInt32(Diam1.Text);
         
    }

соответственно, комбобоксов будет по числу кругов.
По моему пониманию («позавчера впервые открыл книгу по C#») для того, чтобы нарисовать круг, мне понадобится после кода обработчика «Diam1SelectedIndexChanged» каким-то образом вставить код, создающий объект класса Krug с полями, присущими этому объекту — часть унаследована от класса, а часть (диаметр) — получена из комбобокса.
Куда и что вписать?



0



Даценд

Эксперт .NET

5868 / 4745 / 2940

Регистрация: 20.04.2015

Сообщений: 8,361

23.07.2016, 17:57

2

Sumen,
Рисовать в классе круга не нужно.
Я дам пример. Думаю, разберетесь.

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
 
    List<Krug> list = new List<Krug>(); //список кругов
 
    private void Form1_Paint(object sender, PaintEventArgs e) //рисовать лучше здесь
    {
        Pen pen = new Pen(Color.Red);
        foreach (Krug krug in list)
        {
            e.Graphics.DrawEllipse(pen, krug.X, krug.Y, krug.Diam, krug.Diam);
        }
    }
 
    private void btnAdd_Click(object sender, EventArgs e) //кнопка Добавить
    {
        int x = int.Parse(tbX.Text); //текстбокс Х
        int y = int.Parse(tbY.Text); //текстбокс Y
        int d = int.Parse(cbDiam.SelectedItem.ToString()); //комбобокс с диаметром
        list.Add(new Krug(d, x, y)); //добавляем круг в список
        this.Invalidate(); //перерисовываем форму
    }
 
}
 
class Krug
{
    public int Diam { set; get; }
    public int X { set; get; }
    public int Y { set; get; }
    public Krug(int d, int x, int y)
    {
        this.Diam = d;
        this.X = x;
        this.Y = y;
    }
}



0



241 / 243 / 27

Регистрация: 30.01.2014

Сообщений: 1,145

Записей в блоге: 2

25.07.2016, 14:19

 [ТС]

3

Даценд, Спасибо, буду разбираться.



0



Sumen

241 / 243 / 27

Регистрация: 30.01.2014

Сообщений: 1,145

Записей в блоге: 2

28.07.2016, 17:35

 [ТС]

4

Что-то не получилось.
Решил немного видоизменить: координаты x,y — статические, а отрисовку запустить от обработчика события комбобокса:

C#
1
2
3
4
5
6
7
8
9
 
private void DiamSelectedIndexChanged(object sender, EventArgs e) //выбор диаметра в комбобоксе
    {
        int x = 100;
        int y = 100;
        int d = int.Parse(Diam.SelectedItem.ToString()); //комбобокс с диаметром
        list.Add(new Krug(d, x, y)); //добавляем круг в список
        this.Invalidate(); //перерисовываем форму
    }

все остальное — без изменений. Форма прорисовывается, комбобокс тупо переключается. Круг не рисуется.



0



Даценд

Эксперт .NET

5868 / 4745 / 2940

Регистрация: 20.04.2015

Сообщений: 8,361

28.07.2016, 18:33

5

Цитата
Сообщение от Sumen
Посмотреть сообщение

Круг не рисуется.

Вижу 2 возможных ошибки:
1) не подключен к событию обработчик DiamSelectedIndexChanged
2) не подключен к событию обработчик Form1_Paint
Потому что вот полностью код:

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public partial class Form1 : Form
{
 
    public Form1()
    {
        InitializeComponent();
    }
 
    List<Krug> list = new List<Krug>(); //список кругов
 
    private void Form1_Load(object sender, EventArgs e)
    {
        Diam.SelectedIndexChanged += DiamSelectedIndexChanged;
        this.Paint += new PaintEventHandler(Form1_Paint);
    }
 
    private void Form1_Paint(object sender, PaintEventArgs e) //рисовать лучше здесь
    {
        Pen pen = new Pen(Color.Red);
        foreach (Krug krug in list)
        {
            e.Graphics.DrawEllipse(pen, krug.X, krug.Y, krug.Diam, krug.Diam);
        }
    }
 
    private void DiamSelectedIndexChanged(object sender, EventArgs e) //выбор диаметра в комбобоксе
    {
        int x = 100;
        int y = 100;
        int d = int.Parse(Diam.SelectedItem.ToString()); //комбобокс с диаметром
        list.Add(new Krug(d, x, y)); //добавляем круг в список
        this.Invalidate(); //перерисовываем форму
    }
 
 
}
class Krug
{
    public int Diam { set; get; }
    public int X { set; get; }
    public int Y { set; get; }
    public Krug(int d, int x, int y)
    {
        this.Diam = d;
        this.X = x;
        this.Y = y;
    }
}

Вот результат (круги диаметрами 20, 50, 70, 100, 150):

Миниатюры

Рисование кругов
 



0



241 / 243 / 27

Регистрация: 30.01.2014

Сообщений: 1,145

Записей в блоге: 2

28.07.2016, 18:34

 [ТС]

6

Создал вообще новый проект — только поля, комбобокс и кнопка, скопипастил туда код — не рисует((
Код — не тот, который «полностью» из спойлера.



0



Даценд

Эксперт .NET

5868 / 4745 / 2940

Регистрация: 20.04.2015

Сообщений: 8,361

28.07.2016, 18:50

7

Цитата
Сообщение от Sumen
Посмотреть сообщение

скопипастил туда код — не рисует((

Мало скопипастить. Нужно обработчики подписать.
Код под спойлером с динамическим подключением обработчиков. Хотя нет, там нужно Form_Load подписывать.
Код из текущего сообщения можно просто копипастить. На форме нужен только комбобокс с именем Diam:

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public partial class Form1 : Form
{
 
    public Form1()
    {
        InitializeComponent();
        Diam.SelectedIndexChanged += DiamSelectedIndexChanged;
        this.Paint += new PaintEventHandler(Form1_Paint);
    }
 
    List<Krug> list = new List<Krug>(); //список кругов
 
    private void Form1_Paint(object sender, PaintEventArgs e) //рисовать лучше здесь
    {
        Pen pen = new Pen(Color.Red);
        foreach (Krug krug in list)
        {
            e.Graphics.DrawEllipse(pen, krug.X, krug.Y, krug.Diam, krug.Diam);
        }
    }
 
    private void DiamSelectedIndexChanged(object sender, EventArgs e) //выбор диаметра в комбобоксе
    {
        int x = 100;
        int y = 100;
        int d = int.Parse(Diam.SelectedItem.ToString()); //комбобокс с диаметром
        list.Add(new Krug(d, x, y)); //добавляем круг в список
        this.Invalidate(); //перерисовываем форму
    }
 
 
}
class Krug
{
    public int Diam { set; get; }
    public int X { set; get; }
    public int Y { set; get; }
    public Krug(int d, int x, int y)
    {
        this.Diam = d;
        this.X = x;
        this.Y = y;
    }
}



0



Sumen

241 / 243 / 27

Регистрация: 30.01.2014

Сообщений: 1,145

Записей в блоге: 2

28.07.2016, 19:02

 [ТС]

8

Хоть убейте — не понимаю.
Создал новый проект, там combobox с именем Diam и набором чисел. Копипаст всего кода, вставляю его после

C#
1
2
namespace WindowsFormsApplication1
{

запускаю. Результат: только комбобокс.
Гоню. Рисует.

Добавлено через 5 минут
Осталось только это переварить.
Вопросы дальше:
— окружность рисуем, хочется полупрозрачный круг;
— как сделать, чтобы после выбора другого значения рисовался круг вместо этого (ну вроде как уничтожался предыдущий)? Нарисовать такой же цветом фона — «не комильфо».



0



  • Remove From My Forums
  • Question

  • I have a WinForms application that interacts with a connection. If the connection is fine I want to show a green filled circle, if not I want to show a red filled circle.

    I found no circle element in the toolbox so I think I have to draw it on my own.

    I created a picture box called picBoxClientState and
    started with this code

    public partial class FrmMain : Form
    {
        public void CheckSignedInState()
        {
            // some other code
    
            DrawClientStateIcon(client.IsSignedIn);
        }
    
        private void DrawClientStateIcon(bool isSignedIn)
        {
            Point rectangleLocation = picBoxClientState.Location;
            Size rectangleSize = picBoxClientState.Size;
            Rectangle rectangle = new Rectangle(rectangleLocation, rectangleSize);
    
            Color iconColor = isSignedIn ? Color.Green : Color.Red;
            SolidBrush iconBrush = new SolidBrush(iconColor);
    
            Graphics graphics = picBoxClientState.CreateGraphics();
            graphics.FillEllipse(iconBrush, rectangle);
        }
    }

    The debugger reaches the line of code but nothing gets drawn. How can I draw on this element whenever I call CheckSignedInState() ?

    Maybe there is a better way instead of drawing on a picturebox? (I don’t want to toggle two
    images because there might be more states to draw)

    • Edited by

      Tuesday, August 14, 2018 9:24 AM

Basic overview of drawing in C#

How to use the Graphics class to draw to the screen in C#

The Graphics class is one of the fundamental classes used in programming with Windows Forms and GDI+. Through the Graphics class, you gain access to information about the display resolution and device capabilities. In this article, you’ll learn about the Paint event and how it supplies you regarding an adequately initialized Graphics object. This article also covers the most common operations performed using the Graphics object.

The first thing we will do is open Visual Studio and click “Create a new project” to get started. We are going to create a new Windows Form in C#. You could choose any project name you would like and its destined location on your desktop/pc. 

A blank project will be generated to serve as your canvas. You could change the width and height based on your preference. The next thing we need to handle is the paint event for the form. When the form is drawing itself, it will call this paint event, and then inside of that, we will get a handle to the graphics object. Afterward, we could paint the form ourselves. It is a step-by-step process that we need to accomplish. 

Declare a new graphics object with this syntax above. With this step, we could make new shapes like rectangles. 

How to draw a rectangle

To draw rectangles and squares in C#, the GraphicsObject provides the DrawRectangle() method. There are two ways to use the DrawRectangle() method. We will begin by drawing a rectangle without a pre-created Rectangle object.

  • The first step is to create a new brush. The syntax above is the code that you can use to alter the color and name of the brush.
  • It also needs the coordinates of the rectangle you want to create. To do that, you can encode the x, y coordinates like in the syntax attached. 

  • Since we’ve used 100×100 as the coordinates, it came out as square, but you could change the coordinates to generate your desired shape.

For the second method

  • To draw a rectangle, you will draw four lines. We will make a drawing pin and set that equal a new pen in this method. You could also set the color for your rectangle. The syntax above is the example that will generate your rectangle. 

How to draw a circle

Ellipses and circles are drawn in C# using the DrawEllipse() method of the GraphicsObject class. 

We made a drawing scene representing the “sun,” a circle in one of our examples. 

  • You could declare a “new brush” to create the round object. The syntax above shows the various brushes for different objects: the ground and the sun in the said scene.

  • An ellipse will be generated using the declared sun brush and filled with this syntax in the next step.

How to draw a line

Lines are drawn in C# using the DrawLine() method of the Graphics Object. This method takes a pre-instantiated Pen object and two sets of x and y coordinates (the start and endpoints of the line) as arguments.

A “ground” was made to complete the drawing scene in the example. A straight line represents it. 

Coordinates were also filled up to determine the width, height, and length to set up the ground.

The next step in this project is to try drawing a person! A stickman person, to be exact. It will be composed of a circle for its head, a line for its limbs and body.

  • We added another drawing pen to change its color, white. 

In the syntax above, we tried to make a whole component to make a stickman. With various lines and objects, it resulted in the image below. 

The background is also changed to the color blue! And there you go, a scene with a stickman was made using simple objects and lines. 

How to draw an image

To draw an image, it will require creating a bitmap from the file. To do this, the syntax below will help to run the image.  We will use the image above as the background for our generated image.

The syntax above draws the image, but the problem is that our form and image aren’t the exact sizes.  We could stretch the image to fit the form by doing a new rectangle.

The image will be stretched to fit the form better with this code. 

We will also try to attach some images to the scene. We will do next to draw an image bitmap from the file again. 

The attached image is quite big, so you could opt for a smaller size of the image you want. 

This is the revised image of the cat once you’ve scaled it correctly. 

Here is the complete syntax for the background and the cat. Make sure to layer your drawings correctly to make them appear in the correct order. After the cat image, we will draw the bird. 

Here is the image after the code for the bird image is generated and run. 

To add an extra effect, we will add a line object in the scene. 

The last thing that we will add to this project is text. To include text in your image, follow this syntax below. Make sure to set a font style first!

The text is added and repeated three times. The project is done!

This article shows how various graphical objects can be drawn within a drawing programmatically using C#. It may be quite challenging, but first but with troubleshooting, patience, and creativity, you could also finish a project in no time!

  • Windows form c background image
  • Windows forms как создать файл
  • Windows form ссылка на объект не указывает на экземпляр объекта
  • Windows forms как запретить изменять размер окна
  • Windows forms для visual studio 2022