Удобнее всего сделать повторно используемый пользовательский контрол:
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);
}
- Use the
Drawing.Ellipse()
Method to Draw Circles inC#
- Use the
FillEllipse()
Method to Fill Circles inC#
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.
Switch over to the EVENTS
section.
Inside the EVENTS
section now, scroll down till you find the PAINT
and double click on it to produce the 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:
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:
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 Метки нет (Все метки)
Задача:
Вставил бокс с передаваемым значением D:
соответственно, комбобоксов будет по числу кругов.
0 |
Даценд 5868 / 4745 / 2940 Регистрация: 20.04.2015 Сообщений: 8,361 |
||||
23.07.2016, 17:57 |
2 |
|||
Sumen,
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 |
|||
Что-то не получилось.
все остальное — без изменений. Форма прорисовывается, комбобокс тупо переключается. Круг не рисуется.
0 |
Даценд 5868 / 4745 / 2940 Регистрация: 20.04.2015 Сообщений: 8,361 |
||||
28.07.2016, 18:33 |
5 |
|||
Круг не рисуется. Вижу 2 возможных ошибки: Кликните здесь для просмотра всего текста
Вот результат (круги диаметрами 20, 50, 70, 100, 150): Миниатюры
0 |
241 / 243 / 27 Регистрация: 30.01.2014 Сообщений: 1,145 Записей в блоге: 2 |
|
28.07.2016, 18:34 [ТС] |
6 |
Создал вообще новый проект — только поля, комбобокс и кнопка, скопипастил туда код — не рисует((
0 |
Даценд 5868 / 4745 / 2940 Регистрация: 20.04.2015 Сообщений: 8,361 |
||||
28.07.2016, 18:50 |
7 |
|||
скопипастил туда код — не рисует(( Мало скопипастить. Нужно обработчики подписать. Кликните здесь для просмотра всего текста
0 |
Sumen 241 / 243 / 27 Регистрация: 30.01.2014 Сообщений: 1,145 Записей в блоге: 2 |
||||
28.07.2016, 19:02 [ТС] |
8 |
|||
Хоть убейте — не понимаю.
запускаю. Результат: только комбобокс. Добавлено через 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 codepublic 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
-
Edited by
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!