Рисование фигур c windows forms

See how you can draw shapes, use colors, and render images in a WinForms app.

Computer sitting on table open to an image inside a software

Windows Forms is a framework that lets you build desktop applications. You can click and drag components like buttons onto a visual user interface. It also helps you manually create various shapes within your code.

This article will show you how to add lines, shapes, and images to your application. This tutorial uses the Visual Studio 2019 Community Edition to show examples.

What Are the Built-In Classes Used for Drawing Graphics?

Windows Forms uses the C# programming language. Its built-in classes and methods allow you to draw various shapes onto a Windows Form canvas. These include the Graphics, Pen, Color, and Brush classes.

Class

Description

Graphics

The Graphics class allows you to draw shapes and lines onto the canvas. It includes methods such as:

  • DrawLine(Pen, Point1, Point2)
  • DrawRectangle(x, y, width, height)
  • DrawPolygon(Pen, PointF[])

Pen

The Pen class allows you to specify the properties of a ‘pen’ tip which you can use to draw your shapes. You can specify properties such as color, thickness, or dash style. Methods include:

  • SetLineCap(LineCap, LineCap, DashCap)

Color

A color object made up of R (red), G (green), and B (blue) values. You will need a color object for many of the built-in methods that create shapes.

SolidBrush, HatchBrush, TextureBrush

These brush classes derive from the «Brush» interface. These classes allow you to color in blank spaces on the canvas. You can also choose to fill the spaces using different patterns or textures. You can specify properties such as the color.

Rectangle, Line, Polygon, Ellipse

You can create objects based on these shapes, and use them when calling methods such as DrawRectangle(). Instead of passing the x, y, width, and height as arguments, you can choose to pass an existing Rectangle object instead.

To view the source code for a running example of the above tutorial, visit the GitHub repository. You can try out the following examples once you’ve created a Winforms application.

How to Add a Paint on Form Load Event Handler

First, add an event handler to draw shapes when the canvas loads.

  1. Add a Paint function for the form.
     private void Form1_Paint(object sender, PaintEventArgs e)
    {
        // Code goes here
    }
  2. Go into the Design View Tab.
  3. In the Properties window, select the lightning icon to open the «Events» tab.
  4. In «Paint», under «Appearance», select the Form1_Paint function. This will execute the function when you run the application.
    Winforms showing how to add a paint event

How to Draw Lines Onto a Windows Form Canvas

You can use a Color, Pen, and the DrawLine() method to draw lines on a canvas.

  1. Inside the Form1_Paint() function, create a Color object with the color you want the line to be. Then, create a Pen object to draw the line with.
     Color black = Color.FromArgb(255, 0, 0, 0);
    Pen blackPen = new Pen(black);
  2. The DrawLine() method from the Graphics class will draw a line using the pen. This will start drawing a line from an x, y position to another x, y position.
     e.Graphics.DrawLine(blackPen, 300, 200, 800, 200);
  3. You can modify the properties for the pen object to change its width, dash style, and start or end cap.
     blackPen.Width = 20;
    blackPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
    blackPen.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
    e.Graphics.DrawLine(blackPen, 300, 200, 800, 200);
  4. Press the green play button at the top of Visual Studio to see the changes.
    Visual Studio App running with a line

How to Draw Shapes Such as Rectangles and Circles

You can use the shapes classes for different shapes, or draw shapes manually onto the canvas.

  1. Create a Color and Pen object as shown in the previous steps. Then, use the DrawRectangle() method to create the rectangle. The arguments are the x and y coordinates for the top-left of the rectangle, along with its width and height.
     Color red = Color.FromArgb(255, 255, 0, 0);
    Pen redPen = new Pen(red);
    redPen.Width = 5;
    e.Graphics.DrawRectangle(redPen, 100, 100, 500, 200);
  2. You can also create a rectangle using the Rectangle Class. First, create a Rectangle object. The arguments are also the x and y coordinates for the top-left corner, width, and height.
     Rectangle rectangle = new Rectangle(100, 350, 500, 200);
  3. Use the DrawRectangle() function to draw the rectangle. Instead of passing the x, y, width, and height like before, you can use the Rectangle object instead.
     e.Graphics.DrawRectangle(redPen, rectangle);
  4. Press the green play button at the top of Visual Studio to see the changes.
    Visual Studio application running to show rectangles
  5. Go back to the code to draw other shapes. Use the DrawEllipse() function to draw a circle.
     Color green = Color.FromArgb(255, 0, 255, 0);
    Pen greenPen = new Pen(green);
    greenPen.Width = 5;
    e.Graphics.DrawEllipse(greenPen, 400, 150, 400, 400);

    When you draw a circle, the x and y coordinates (x=400, y=150) refer to the top-left corner of the circle, not the center of the circle.

    Close up example of circle on canvas and where X,Y starts
  6. To draw other shapes such as triangles or hexagons, use the DrawPolygon() method. Here you can specify a list of coordinates to represent the points of the shape.
     Color blue = Color.FromArgb(255, 0, 0, 255);
    Pen bluePen = new Pen(blue);
    bluePen.Width = 5;

    PointF[] coordinatesForTriangle = new PointF[] {
        new PointF(400, 150),
        new PointF(300, 300),
        new PointF(500, 300)
    };

    e.Graphics.DrawPolygon(bluePen, coordinatesForTriangle);

    The DrawPolygon() method will draw lines between the points specified.

    Visual Studio app running to show triangle on canvas

    ​​​​​​

How to Use the Brush Class to Fill In Shapes With Color

You can use the FillRectangle(), FillEllipses() or FillTriangle() methods to create shapes with a solid color.

  1. First, create a brush object.
     Color purple = Color.FromArgb(255, 128, 0, 0);
    SolidBrush solidBrush = new SolidBrush(purple);
  2. Use the FillRectangle(), FillEllipses() or FillTriangle() methods. They work the same way as the draw functions above, except instead of a Pen, they use a Brush object.
     e.Graphics.FillRectangle(solidBrush, 50, 50, 200, 250);
    e.Graphics.FillEllipse(solidBrush, 300, 50, 200, 200);
    e.Graphics.FillPolygon(solidBrush, new PointF[] { new PointF(700, 150), new PointF(600, 300), new PointF(800, 300) });
    Visual Studio app running to show filled shapes on canvas
  3. You can also input a shape object directly instead of providing coordinates.
     Rectangle rectangle = new Rectangle(100, 350, 500, 200);
    e.Graphics.FillRectangle(solidBrush, rectangle);
  4. Use the HatchBrush to fill the shape using a different fill style, such as a horizontal or vertical pattern.
     Color blue = Color.FromArgb(255, 0, 0, 255);
    Color green = Color.FromArgb(255, 0, 255, 0);
    HatchBrush hatchBrush = new HatchBrush(HatchStyle.Horizontal, green, blue);
    e.Graphics.FillRectangle(hatchBrush, 50, 50, 200, 250);
    Visual Studio app open to show rectangle with horizontal pattern design fill
  5. You can use the TextureBrush to fill a shape using an image. Here, create a bitmap by pointing to an image file. Instead of creating a brush using a color, create it using the image.
     Bitmap image = (Bitmap)Image.FromFile(@"C:\Users\Sharl\Desktop\flag.bmp", true);
    TextureBrush textureBrush = new TextureBrush(image);
    e.Graphics.FillRectangle(textureBrush, 100, 100, 500, 400);
    Visual Studio app open to show shape filled using an image

How to Render Images Onto the Form

To render an image, create a PictureBox control object and add it to the form.

  1. Create a PictureBox control object using an image file.
     PictureBox picture = new PictureBox();
    picture.ImageLocation = @"C:\Users\Sharl\Desktop\flagLarge.bmp";
  2. Set the size of the image and add it onto the form so it renders.
     picture.SizeMode = PictureBoxSizeMode.AutoSize;
    this.Controls.Add(picture);
  3. Press the green start button at the top to view the image.
    Winforms App open to show image rendered on form

Adding More Shapes to Your Windows Form

You should now understand how to add lines, shapes, and images to your Windows form. You can combine shapes to create new shapes. You can also play around with the built-in functions to create more complex shapes.

Introduction

GDI+ consists of the set of .NET base classes that are available to control custom drawing on the screen. These classes arrange for the appropriate instructions to be sent to the graphics device drivers to ensure the correct output is placed on the screen. GDI provides a level of abstraction, hiding the differences between different video cards. You simply call on the Windows API function to do the specific task, and internally the GDI figures out how to get the client’s particular video card to do whatever it is you want when they run your particular piece of code.

Not only this, but the client has several display devices — for example — monitors and printers — GDI achieves the task of making the printer look the same onscreen as far as the application is concerned. If the client wants to print something instead of displaying it, your application will simply inform the system that the output device is the printer and then call the same API functions in exactly the same way. As you can see, the device-context (DC) object is a very powerful mechanism. Having said that, we can also use this layer of abstraction to draw onto a Windows Form. This paper will therefore begin with an example of a  basic Windows Forms development in order to demonstrate how to draw graphics onto a Windows Form, or a control on that form. The focus of this article will be on graphics.

The Form object is used to represent any Window in your application. When creating a main window, you must follow two mandatory steps:

  1. Derive a new custom class from System.Windows.Forms.Form
  2. Configure the application’s Main() method to call System.Windows.Forms.Application.Run(), passing an instance of your new Form derived as a class argument.

Here is an example:

C# File: MyForm.cs

using System;
using System.Windows.Forms;
public class MyForm : System.Windows.Forms.Form
{
    public MyForm()
    {
        Text = "No Graphics";
    }
    public static void Main()
    {
        Application.Run(new MyForm());
    }
}

To compile:

C:\Windows\Microsoft.NET\Framework\v2.050727>csc /target:winexe MyForm.cs

So now we have a blank form. So what do we do to learn how to use graphics? If you use Visual Studio 2005 you probably know that the .NET Framework 2.0  supports partial classes. With Visual Studio 2005, a Windows Form is completely defined with a single C# source file. The code generated by the IDE was separated from your code by using regions, therefore taking advantage of partial classes.

By default, each form named Form111 corresponds to two files; Form111.cs which contains your code and Form111.Designer.cs, which contains the code generated by the IDE. The code, however, is usually generated by dragging and dropping controls. One of the simplest uses for the System.Drawing namespace is specifying the location of the controls in a Windows Forms application. More to the point, user-defined types are often referred to as structures.

To draw lines and shapes you must follow these steps:

  1. Create a Graphics object by calling System.Windows.Forms.Control.CreateGraphics method. The Graphics object contains the  Windows DC you need to draw with. The device control created is associated with the display device, and also with the Window.

  2. Create a Pen object

  3. Call a member of the Graphics class to draw on the control using the Pen

Here is an example of a Form with a line drawn at a 60 degree angle from the upper-most left hand corner:

//File: DrawLine.cs
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
public class MainForm : System.Windows.Forms.Form
{
    private System.ComponentModel.Container components;
    public MainForm()
    {
        InitializeComponent();
        CenterToScreen();
        SetStyle(ControlStyles.ResizeRedraw, true); 
    } 
    //  Clean up any resources being used.
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (components != null)
            {
                components.Dispose();
            }
        }
        base.Dispose(disposing);
    }
    #region Windows Form Designer generated code
    private void InitializeComponent()
    {
        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(292, 273);
        this.Text = "Fun with graphics";
        this.Resize += new System.EventHandler(this.Form1_Resize);
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); 
    }
    #endregion 
    [STAThread]
    static void Main()
    {
        Application.Run(new MainForm());
    }
    private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    {
        //create a graphics object from the form
        Graphics g = this.CreateGraphics();
        // create  a  pen object with which to draw
        Pen p = new Pen(Color.Red, 7);  // draw the line 
        // call a member of the graphics class
        g.DrawLine(p, 1, 1, 100, 100);
    }
    private void Form1_Resize(object sender, System.EventArgs e)
    {
        // Invalidate();  See ctor!
    }
}

TO COMPILE:

csc.exe /target:winexe DrawLine.cs

Typically, you specify the Pen class color and width in pixels with the constructor. The code above draws a 7-pixel wide red line from the upper-left corner (1,1,) to a point near the middle of the form (100, 100).  Note the following code that draws a pie shape:

//File: DrawPie.cs
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
public class MainForm : System.Windows.Forms.Form
{
    private System.ComponentModel.Container components;
    public MainForm()
    {
        InitializeComponent();
        CenterToScreen();
        SetStyle(ControlStyles.ResizeRedraw, true);
    }
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (components != null)
            {
                components.Dispose();
            }
        }
        base.Dispose(disposing);
    }
    #region Windows Form Designer generated code
    //
    private void InitializeComponent()
    {
        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(292, 273);
        this.Text = "Fun with graphics";
        this.Resize += new System.EventHandler(this.Form1_Resize);
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); 
    }
    #endregion
    [STAThread]
    static void Main()
    {
        Application.Run(new MainForm());
    }
    private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    { 
        //create a graphics object from the form
        Graphics g = this.CreateGraphics();
        Pen p = new Pen(Color.Blue, 3);
        g.DrawPie(p, 1, 1, 100, 100, -30, 60);
    }
    private void Form1_Resize(object sender, System.EventArgs e)
    {
    }
}

To compile:

csc.exe /target:winexe DrawPie.cs

A structure, or «struct», is a cut-down class that does almost everything a class does, except support inheritance and finalizers. A structure is a composite of other types that make easier to work with related data. The simplest example is  System.Drawing.Point, which contain X and Y integer properties that define the horizontal and vertical coordinates of a point.

The Point structure simplifies working with coordinates by providing constructors and members as follows:

// Requires reference to System.Drawing
// Create point
System.Drawing.Point p = new System.Drawing.Point(20, 20);
// move point diagonally
p.Offset(-1, -1)
Console.WriteLine("Point X {0}, Y {1}", p.X, p.Y.);

So as the coordinates of a point define its location, this process also specifies a control’s location. Just create a new Point structure by specifying the coordinates relative to the upper-left corner of the form, and use the Point to set the control’s Location property.

Graphics.DrawLines, Graphics.DrawPolygons, and Graphics.DrawRectangles accept arrays as parameters to help you draw more complex shapes:

Here is an example of a polygon, but with its contents filled. Notice the code responsible for filling the shape:

DrawPolygonAndFill.cs

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data; 
public class MainForm : System.Windows.Forms.Form
{
    private System.ComponentModel.Container components;
    public MainForm()
    {
        InitializeComponent();
        CenterToScreen();
        SetStyle(ControlStyles.ResizeRedraw, true);
    }
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (components != null)
            {
                components.Dispose();
            }
        }
        base.Dispose(disposing);
    }
    #region Windows Form Designer generated code
    private void InitializeComponent()
    {
        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(292, 273);
        this.Text = "Fun with graphics";
        this.Resize += new System.EventHandler(this.Form1_Resize);
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); 
    }
    #endregion
    [STAThread]
    static void Main()
    {
        Application.Run(new MainForm());
    }
    private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    {
        //create a graphics object from the form
        Graphics g = this.CreateGraphics();
        Brush b = new SolidBrush(Color.Maroon);
        Point[] points = new Point[]
        {
            new Point(10, 10),
            new Point(10, 100),
            new Point(50, 65),
            new Point(100, 100),
            new Point(85, 40)};   // Notice the braces, as used in structures
            g.FillPolygon(b, points);
        }
    }
    private void Form1_Resize(object sender, System.EventArgs e)
    {
    }
}

Customizing Pens

The color and size of a pen is specified in the Pen constructor, so you can manipulate the pattern and the endcaps. The endcaps are the end of the line, and you can use them to create arrows and other special effects. While pens by default draw straight lines, their properties can be set to one of these values: DashStyle.Dash, DashStyle.DashDot, DashStyle.DashDotDot, DashStyle.Dot, or DashStyle.Solid. Consider this final example:

UsePen.cs

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
public class MainForm : System.Windows.Forms.Form
{
    private System.ComponentModel.Container components;
    public MainForm()
    { 
        InitializeComponent();
        CenterToScreen();
        SetStyle(ControlStyles.ResizeRedraw, true); 
    } 
    //  Clean up any resources being used.
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (components != null)
            {
                components.Dispose();
            }
        }
        base.Dispose(disposing);
    } 
    #region Windows Form Designer generated code
    private void InitializeComponent()
    {
        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(292, 273);
        this.Text = "Learning graphics";
        this.Resize += new System.EventHandler(this.Form1_Resize);
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); 
    }
    #endregion 
    [STAThread]
    static void Main()
    {
        Application.Run(new MainForm());
    }
    private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    { 
        //create a graphics object from the form
        Graphics g = this.CreateGraphics();
        // create a Pen object
        Pen p = new Pen(Color.Red, 10);
        p.StartCap = LineCap.ArrowAnchor;
        p.EndCap = LineCap.DiamondAnchor;
        g.DrawLine(p, 50, 25, 400, 25);
        p.StartCap = LineCap.SquareAnchor;
        p.EndCap = LineCap.Triangle;
        g.DrawLine(p, 50, 50, 400, 50);
        p.StartCap = LineCap.Flat;
        p.EndCap = LineCap.Round;
        g.DrawLine(p, 50, 75, 400, 75);
        p.StartCap = LineCap.RoundAnchor;
        p.EndCap = LineCap.Square;
        g.DrawLine(p, 50, 100, 400, 100);
    }
    private void Form1_Resize(object sender, System.EventArgs e)
    {
        // Invalidate();  See ctor!
    }
}

The basics underlying principles in this paper indicate the location and size of points so that they for a line or a shape. This should the new developer to understand that these principles can be expanded upon to specify the size and location of controls that are dragged and dropped onto a Windows Form. For instance, if we were to start Visual Studio 2005 and begin a Forms application, we could set that Form background color to white. The designer file and the source file that comprise the application would both reflect that property: the setting of the property would cause the IDE to generate the code in the Form.Designer.cs file. Well, that all for now. 

DrawLine.cs

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
public class MainForm : System.Windows.Forms.Form
{ 
    private System.ComponentModel.Container components; 
    public MainForm()
    { 
        InitializeComponent();
        CenterToScreen();
        SetStyle(ControlStyles.ResizeRedraw, true); 
    } 
    //  Clean up any resources being used.
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (components != null)
            {
                components.Dispose();
            }
        }
        base.Dispose(disposing);
    }
    #region Windows Form Designer generated code
    private void InitializeComponent()
    {
        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(292, 273);
        this.Text = "Learning graphics";
        this.Resize += new System.EventHandler(this.Form1_Resize);
        this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); 
    }
    #endregion 
    [STAThread]
    static void Main()
    {
        Application.Run(new MainForm());
    }
    private void MainForm_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    { 
        //create a graphics object from the form
        Graphics g = this.CreateGraphics();
        // create  a  pen object with which to draw
        Pen p = new Pen(Color.Red, 7);
        // draw the line
        g.DrawLine(p, 1, 1, 100, 100);
    }
    private void Form1_Resize(object sender, System.EventArgs e)
    {
        // Invalidate();  See ctor!
    }
}

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!

Нарисуем корабль, например, такой:

Кораблик

Ваши действия:

1) Создайте приложение Windows Forms,  namespace = «Кораблик».
2) Размер формы задайте 900х500, на ней разместите визуальный объект для рисования pictureBox1, измените его свойство Dock = Fill; (он займет все пространство формы).
3) Кликнув на компоненте, вы создадите событие pictureBox1.Click и форму для метода обработки этого события pictureBox1_Click ();
4) Не забудьте добавить библиотеку System.Drawing. Ненужные библиотеки можно удалить (нужны всего три: System, System.Windows.Forms и System.Drawing).
5) В окне кода файла Form1.cs получите следующий текст:

using System;
using System.Drawing;
using System.Windows.Forms;
namespace Кораблик
{
   public partial class Form1 : Form
   {
     public Form1()
     {
       InitializeComponent();
     }
     private void pictureBox1_Click(object sender, EventArgs e)
     {
       ...
     }
   }
}

Теперь нам осталось только написать обработчик события, добавленный нами метод  pictureBox1_Click ( ), для чего вставим следующие операторы с комментариями:

 // Объявляем объект "g" класса Graphics и предоставляем
 // ему возможность рисования на pictureBox1:
  Graphics g = pictureBox1.CreateGraphics();
  g.Clear(Color.Turquoise);
 // Создаем объекты-кисти для закрашивания фигур
  SolidBrush myCorp = new SolidBrush(Color.DarkMagenta);
  SolidBrush myTrum = new SolidBrush(Color.DarkOrchid);
  SolidBrush myTrub = new SolidBrush(Color.DeepPink);
  SolidBrush mySeа = new SolidBrush(Color.Blue);
 //Выбираем перо myPen желтого цвета толщиной в 2 пикселя:
  Pen myWind = new Pen(Color.Yellow, 2);
 // Закрашиваем фигуры
  g.FillRectangle(myTrub,300,125,75,75); // 1 труба (прямоугольник)
  g.FillRectangle(myTrub,480,125,75,75); // 2 труба (прямоугольник)
  g.FillPolygon(myCorp, new Point[]      // корпус (трапеция)
    {
    new Point(100,300),new Point(700,300),
    new Point(700,300),new Point(600,400),
    new Point(600,400),new Point(200,400),
    new Point(200,400),new Point(100,300)
    }
  );
  g.FillRectangle(myTrum, 250, 200, 350, 100); // палуба (прямоугольник)
 // Море - 12 секторов-полуокружностей
  int x = 50;
  int Radius = 50;
  while (x <= pictureBox1.Width - Radius)
  {
     g.FillPie(mySeа, 0 + x, 375, 50, 50, 0, -180); 
     x += 50;
  }
 // Иллюминаторы 
  for (int y = 300; y <= 550; y += 50)
  {
     g.DrawEllipse(myWind, y, 240, 20, 20); // 6 окружностей
  }

В этом примере мы использовали методы класса Graphics: FillRectangle(), FillPolygon(), FillPie() и DrawEllipse(). Найдите их в таблице предыдущей статьи. Кроме того мы используем структуры Point; oбъекты-кисти класса SolidBrush; объект-перо класса Pen. Для рисования волн моря использовался цикл while, для иллюминаторов — цикл for. Полигон задается массивом точек для соединения их сплошной ломаной.
И все, программу можно проверять. Кликнув в окне, сможем увидеть наш кораблик:
Кораблик

Перейдем к следующему примеру «Рисование контура и закраска произвольной области, ограниченной ломаной прямой».


NEW: Наш Чат, в котором вы можете обсудить любые вопросы, идеи, поделиться опытом или связаться с администраторами.


Помощь проекту:

gorbunov-anton

2 / 2 / 1

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

Сообщений: 56

1

29.10.2014, 21:15. Показов 58525. Ответов 32

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


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

Нужно нарисовать в Form геометрическую фигуру. Я думаю что рисовать нужно на каком-то объекте я взял PictureBox и попытался рисовать на нем, но вышли ошибки, может я что-то не так сделал и есть другие объекты для рисования на них? И еще после того как я нарисовал пробную линию она через несколько секунд исчезла, как сделать чтобы нарисованный объект не исчезал.

Вот мой код:

C#
1
2
3
4
5
6
7
8
private void button1_Click(object sender, EventArgs e)
        {
            Graphics g = this.CreateGraphics(); 
            {
                g.DrawLine(Pens.Black, new Point(0, 0), new Point(20, 100));
 
            }
        }



0



zna926

547 / 478 / 315

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

Сообщений: 3,345

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

29.10.2014, 23:55

3

Привожу код построения, например, эллипса. Аналогично можно строить прямоугольники, многоугольники и пр.

C#
1
2
3
4
5
6
7
8
9
10
11
12
Forms Code
{
 
       private void button1_Click(object sender, EventArgs e)
       {
           Pen pn = new Pen(Color.Black, 5);  // Перо для рисования
            Graphics g = CreateGraphics();
             g.DrawEllipse(pn, 200, 200, 300, 200);  //200, 200 - координаты верхнего левого угла прямоугольника, 
                                         //300, 200 - его ширина и высота. Сюда вписывается эллипс.                        
      }
 
}



0



1120 / 855 / 499

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

Сообщений: 2,023

30.10.2014, 00:02

4

Цитата
Сообщение от gorbunov-anton
Посмотреть сообщение

я нарисовал пробную линию она через несколько секунд исчезла, как сделать чтобы нарисованный объект не исчезал.

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

Аналогично можно строить прямоугольники, многоугольники и пр.

Аналогично исчезнут

Слушайте ViterAlex, он дело говорит



0



gorbunov-anton

2 / 2 / 1

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

Сообщений: 56

30.10.2014, 16:14

 [ТС]

5

Я не могу так свободно читать код без объяснения поэтому по этим ссылкам я мало что усвоил для себя. Я вот сам попытался загрузить изображение в PictureBox при загрузке Form. Но у меня не получилось скажите что я сделал не так ?

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        Bitmap bmp1 = new Bitmap(@"C:\Users\Антон\Desktop\Kursovoi project\fon.jpg");
 
        private void Form1_Load(object sender, System.EventArgs e)
        { pictureBox1.Image = bmp1; }
 
        private void button1_Click(object sender, EventArgs e)
        {
            Graphics g = this.CreateGraphics(); 
            {
                g.DrawLine(Pens.Black, new Point(0, 0), new Point(20, 100));
 
            }
        }



0



zna926

547 / 478 / 315

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

Сообщений: 3,345

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

30.10.2014, 17:40

6

Ошибка в твоем коде, что не указана толщина линии.
Сейчас ничего не исчезнет.

C#
1
2
3
4
5
6
7
8
9
10
11
12
Forms Code
{
 
       private void button1_Click(object sender, EventArgs e)
       {
          Pen pn= new Pen(color.Black, 5); 
           Graphics g =CreateGraphics();       
             g.DrawLine(pn, new Point(0, 0), new Point(20, 100));
 
       }
 
}



0



2 / 2 / 1

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

Сообщений: 56

30.10.2014, 20:07

 [ТС]

7

Да не исчезает. Теперь понятно. Но мне нужно рисовать на белом фоне. А для этого я думаю надо использовать PictureBox с Bitmap.



0



547 / 478 / 315

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

Сообщений: 3,345

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

30.10.2014, 21:08

8

Непонятно, зачем так сложно.
Установите для формы свойство BackColor белого цвета.



0



ViterAlex

8934 / 4846 / 1886

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

Сообщений: 10,246

30.10.2014, 21:40

9

Чувствую, что пора написать FAQ по рисованию на форме. Ну пока так:

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
using System;
using System.Drawing;
using System.Windows.Forms;
 
namespace WindowsFormsApplication1 {
    public partial class Form1 : Form {
        Bitmap bmp;//Здесь рисуем
        public Form1() {
            InitializeComponent();
            /// В конструкторе формы задаёшь размер Bitmap
            /// Если PictureBox будет менять размер, то нужно использовать событие
            /// Resize, чтобы привести размер битмапа в соотвествие. Или использовать
            /// SizeMode = StretchImage. Но пока просто зададим размер
            bmp = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height);
            /// Обработка нажатия на кнопку. Можно это делать через дизайнер, дважды кликнув по кнопке
            button1.Click += button1_Click;
        }
 
        void button1_Click(object sender, EventArgs e) {
            /// Здесь рисуем на битмап. А затем этот битмап назначаем свойству Image.
            /// Поскольку объекты Graphics нужно сразу уничтожать после использования,
            /// то всегда пользуемся конструкцией using. Она сама уничтожит объект при
            /// выходе.
            using (Graphics g = Graphics.FromImage(bmp)) {
                /// Рисование на белом фоне. Делаем заливку белым цветом
                g.Clear(Color.White);
                g.DrawLine(Pens.Black, 10, 10, 40, 40);
            }
            /// Назначаем наш Bitmap свойству Image
            pictureBox1.Image = bmp;
        }
 
    }
}

На форме только PictureBox и кнопка

Добавлено через 1 минуту

Цитата
Сообщение от gorbunov-anton
Посмотреть сообщение

у меня не получилось скажите что я сделал не так ?

Изображение ты назначил в pictureBox, а рисуешь на форме



1



2 / 2 / 1

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

Сообщений: 56

30.10.2014, 21:51

 [ТС]

10

Да у меня курсовая а там кнопки на сером фоне и белый экранчик на котором происходит рисование. Конечно можно в свойствах PictureBox задать белый цвет, но хотел все по умному сделать, правильно, чтобы кодом а не настройками цвет устанавливался.

Добавлено через 3 минуты
Я понимаю что рисую на форме, но для начала я хотел просто изображение загрузить и не получилось.



0



8934 / 4846 / 1886

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

Сообщений: 10,246

30.10.2014, 22:42

11

Цитата
Сообщение от gorbunov-anton
Посмотреть сообщение

Я понимаю что рисую на форме, но для начала я хотел просто изображение загрузить и не получилось.

Почему? Не загрузилось? Ошибку выдало? Компьютер сгорел?



0



gorbunov-anton

2 / 2 / 1

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

Сообщений: 56

30.10.2014, 23:29

 [ТС]

12

Ну вот например я пытаюсь просто загрузить изображение на PictureBox

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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace Kursovoi
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
 
        private void Form1_Load(object sender, System.EventArgs e)
        {
            Size sz = new Size(this.pictureBox1.Width, this.pictureBox1.Height);
            Bitmap bmp1 = new Bitmap(@"C:\Users\Антон\Desktop\Kursovoi\fon.jpg", sz);
            pictureBox1.Image = bmp1; 
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            Pen pn = new Pen(Color.Black, 5);
            Graphics g = this.CreateGraphics();
            g.DrawLine(pn, new Point(0, 0), new Point(20, 100));
 
 
        }
    }
}

и он пишет:
Ошибка 1 Наиболее подходящий перегруженный метод для «System.Drawing.Bitmap.Bitmap(string, bool)» имеет несколько недопустимых аргументов C:\Users\Антон\Desktop\Kursovoi\Kursovoi\Form1.cs 23 27 Kursovoi
Ошибка 2 Аргумент «2»: преобразование типа из «System.Drawing.Size» в «bool» невозможно C:\Users\Антон\Desktop\Kursovoi\Kursovoi\Form1.cs 23 82 Kursovoi



0



8934 / 4846 / 1886

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

Сообщений: 10,246

30.10.2014, 23:35

13

Правильно пишет. Потому что ты пытаешься загрузить картинку из файла и сразу указать её размер. Почему ты решил, что это возможно? Такого конструктора Bitmap не имеет. Есть отдельный конструктор по имени файла и отдельный по размеру.
При загрузке из файла, размер Bitmap будет установлен в соответствии с размерами изображения в файле



0



2 / 2 / 1

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

Сообщений: 56

31.10.2014, 09:40

 [ТС]

14

А эта конструкция что значит ?

Миниатюры

Рисование в Form геометрических фигур
 



0



2 / 2 / 1

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

Сообщений: 56

03.11.2014, 22:15

 [ТС]

15

Я вот еще подумал, а что не могу я нарисовать изображение прямо на форме зачем для этого нужен picturebox ?



0



547 / 478 / 315

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

Сообщений: 3,345

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

03.11.2014, 22:45

16

Используя рикчербокс, можно перемещать изображение на форме.
Когда то сделал 2 шарика, включил таймер и они двигались по форме, подлетая к ее краю, отражались (при этом угол падения был равен углу отражения и т.д.)



0



gorbunov-anton

2 / 2 / 1

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

Сообщений: 56

03.11.2014, 22:58

 [ТС]

17

Движение можно создать и на форме заливая одну картинку поверх другой.

Почему этот код не работает?

C#
1
2
3
4
5
6
7
8
private void Form1_Load(object sender, EventArgs e)
        {
            
            Rectangle newRec=new Rectangle(50,50,100,100);
            Image newImage=Image.FromFile(@"C:\Users\Антон\Desktop\Kursovoi\fon.jpg");
            Graphics g = CreateGraphics();
            g.DrawImage(newImage, newRec);
        }



0



547 / 478 / 315

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

Сообщений: 3,345

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

04.11.2014, 17:27

18

Очень сложно. Нужно менять координаты рикчербокса



0



2 / 2 / 1

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

Сообщений: 56

04.11.2014, 19:46

 [ТС]

19

Кое-что у меня получилось. Оказывается причина была еще в том что я неправильно событие назвал. Надо было писать не Form1_Load а Form1_Load_1



0



zna926

547 / 478 / 315

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

Сообщений: 3,345

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

04.11.2014, 22:57

20

Думаю, что события тут вообще не нужны. Используется, например, просто форма1, а код движения записывается в

C#
1
2
3
4
  private void timer1_Tick(object sender, EventArgs e)
  {
 
  }



0



  • Ретро игры для windows 10
  • Рисовалка для windows 10 скачать
  • Ресурсы аппаратуры в windows 10
  • Ридер djvu для windows 10
  • Ресурс общего доступа к файлам и принтерам доступен в сети но не отвечает windows 10