How to draw in windows forms

How to: Create Graphics Objects for Drawing

Before you can draw lines and shapes, render text, or display and manipulate images with GDI+, you need to create a Graphics object. The Graphics object represents a GDI+ drawing surface, and is the object that is used to create graphical images.

There are two steps in working with graphics:

Creating a Graphics object.

Using the Graphics object to draw lines and shapes, render text, or display and manipulate images.

Creating a Graphics Object

A graphics object can be created in a variety of ways.

To create a graphics object

Receive a reference to a graphics object as part of the PaintEventArgs in the Paint event of a form or control. This is usually how you obtain a reference to a graphics object when creating painting code for a control. Similarly, you can also obtain a graphics object as a property of the PrintPageEventArgs when handling the PrintPage event for a PrintDocument.

Call the CreateGraphics method of a control or form to obtain a reference to a Graphics object that represents the drawing surface of that control or form. Use this method if you want to draw on a form or control that already exists.

Create a Graphics object from any object that inherits from Image. This approach is useful when you want to alter an already existing image.

The following sections give details about each of these processes.

PaintEventArgs in the Paint Event Handler

When programming the PaintEventHandler for controls or the PrintPage for a PrintDocument, a graphics object is provided as one of the properties of PaintEventArgs or PrintPageEventArgs.

To obtain a reference to a Graphics object from the PaintEventArgs in the Paint event

Declare the Graphics object.

Assign the variable to refer to the Graphics object passed as part of the PaintEventArgs.

Insert code to paint the form or control.

The following example shows how to reference a Graphics object from the PaintEventArgs in the Paint event:

CreateGraphics Method

You can also use the CreateGraphics method of a control or form to obtain a reference to a Graphics object that represents the drawing surface of that control or form.

To create a Graphics object with the CreateGraphics method

Call the CreateGraphics method of the form or control upon which you want to render graphics.

Create from an Image Object

Additionally, you can create a graphics object from any object that derives from the Image class.

Читайте также:  Windows data source file

To create a Graphics object from an Image

Call the Graphics.FromImage method, supplying the name of the Image variable from which you want to create a Graphics object.

The following example shows how to use a Bitmap object:

You can only create Graphics objects from nonindexed .bmp files, such as 16-bit, 24-bit, and 32-bit .bmp files. Each pixel of nonindexed .bmp files holds a color, in contrast to pixels of indexed .bmp files, which hold an index to a color table.

Drawing and Manipulating Shapes and Images

After it is created, a Graphics object may be used to draw lines and shapes, render text, or display and manipulate images. The principal objects that are used with the Graphics object are:

The Pen class—Used for drawing lines, outlining shapes, or rendering other geometric representations.

The Brush class—Used for filling areas of graphics, such as filled shapes, images, or text.

The Font class—Provides a description of what shapes to use when rendering text.

The Color structure—Represents the different colors to display.

To use the Graphics object you have created

Work with the appropriate object listed above to draw what you need.

For more information, see the following topics:

Построение и рисование кривых Constructing and Drawing Curves

GDI+ поддерживает несколько типов кривых: эллипсы, дуги, фундаментальные сплайны и Сплайны Безье. GDI+ supports several types of curves: ellipses, arcs, cardinal splines, and Bézier splines. Эллипс определяется его ограничивающим прямоугольником; дуга — это часть эллипса, определяемая начальным углом и углом поворота. An ellipse is defined by its bounding rectangle; an arc is a portion of an ellipse defined by a starting angle and a sweep angle. Фундаментальный сплайн определяется массивом точек и параметром натяжения — кривая плавно проходит через каждую точку в массиве, а параметр натяжения влияет на изгиб кривой. A cardinal spline is defined by an array of points and a tension parameter — the curve passes smoothly through each point in the array, and the tension parameter influences the way the curve bends. Сплайн Безье определяется двумя конечными точками и двумя контрольными точками. кривая не проходит через контрольные точки, но контрольные точки влияют на направление и изгиб, так как кривая переходит от одной конечной точки к другой. A Bézier spline is defined by two endpoints and two control points the curve does not pass through the control points, but the control points influence the direction and bend as the curve goes from one endpoint to the other.

в этом разделе In This Section

Практическое руководство. Рисование фундаментальных сплайнов How to: Draw Cardinal Splines
Описывает фундаментальные сплайны и способы их рисования. Describes cardinal splines and how to draw them.

Практическое руководство. Рисование отдельного сплайна Безье How to: Draw a Single Bézier Spline
Описывает сплайн Безье и способ его рисования. Describes a Bézier spline and how to draw one.

Практическое руководство. Рисование последовательности сплайнов Безье How to: Draw a Sequence of Bézier Splines
Объясняет, как поочередно нарисовать несколько сплайнов Безье. Explains how to draw several Bézier splines in sequence.

Graphics and Drawing in Windows Forms

The common language runtime uses an advanced implementation of the Windows Graphics Device Interface (GDI) called GDI+. With GDI+ you can create graphics, draw text, and manipulate graphical images as objects. GDI+ is designed to offer performance and ease of use. You can use GDI+ to render graphical images on Windows Forms and controls. Although you cannot use GDI+ directly on Web Forms, you can display graphical images through the Image Web Server control.

Читайте также:  Акселерометр windows 10 драйвер

In this section, you will find topics that introduce the fundamentals of GDI+ programming. Although not intended to be a comprehensive reference, this section includes information about the Graphics, Pen, Brush, and Color objects, and explains how to perform such tasks as drawing shapes, drawing text, or displaying images. For more information, see GDI+ Reference.

If you’d like to jump in and get started right away, see Getting Started with Graphics Programming. It has topics on how to use code to draw lines, shapes, text, and more on Windows forms.

In This Section

Graphics Overview
Provides an introduction to the graphics-related managed classes.

About GDI+ Managed Code
Provides information about the managed GDI+ classes.

Using Managed Graphics Classes
Demonstrates how to complete a variety of tasks using the GDI+ managed classes.

Reference

System.Drawing
Provides access to GDI+ basic graphics functionality.

System.Drawing.Drawing2D
Provides advanced two-dimensional and vector graphics functionality.

System.Drawing.Imaging
Provides advanced GDI+ imaging functionality.

System.Drawing.Text
Provides advanced GDI+ typography functionality. The classes in this namespace can be used to create and use collections of fonts.

Custom Control Painting and Rendering
Details how to provide code for painting controls.

Объекты Graphics и Drawing в Windows Forms Graphics and Drawing in Windows Forms

Среда CLR использует расширенную реализацию Windows интерфейс графических устройств (GDI) с именем GDI+. The common language runtime uses an advanced implementation of the Windows Graphics Device Interface (GDI) called GDI+. С помощью GDI+ можно создавать графики, рисовать текст и манипулировать графическими изображениями как объектами. With GDI+ you can create graphics, draw text, and manipulate graphical images as objects. Интерфейс GDI+ обеспечивает производительность и простоту использования. GDI+ is designed to offer performance and ease of use. GDI+ можно использовать для отрисовки графических изображений на Windows Forms и элементы управления. You can use GDI+ to render graphical images on Windows Forms and controls. Хотя вы не можете использовать GDI+ непосредственно в веб-формах, можно отображать графические изображения с помощью серверного веб-элемента управления Image. Although you cannot use GDI+ directly on Web Forms, you can display graphical images through the Image Web Server control.

В этом разделе вы найдете разделы, в которых представлены основные принципы программирования GDI+. In this section, you will find topics that introduce the fundamentals of GDI+ programming. Хотя он не является полным справочником, в нем содержатся сведения об объектах Graphics, Pen, Brush и Color и способах выполнения таких задач, как рисование фигур, создание текста, отображение рисунков. Although not intended to be a comprehensive reference, this section includes information about the Graphics, Pen, Brush, and Color objects, and explains how to perform such tasks as drawing shapes, drawing text, or displaying images. Дополнительные сведения см. в справочнике по GDI+. For more information, see GDI+ Reference.

Если вы хотите немедленно приступить к работе, см. статью Приступая к программированию графики. If you’d like to jump in and get started right away, see Getting Started with Graphics Programming. Она содержит разделы, посвященные использованию кода для рисования линий, фигур, текста и других элементов в формах Windows Forms. It has topics on how to use code to draw lines, shapes, text, and more on Windows forms.

Читайте также:  Как установить приложение сразу для всех пользователей windows 10

в этом разделе In This Section

Общие сведения о графике Graphics Overview
Общие сведения об управляемых классах, связанных с графикой. Provides an introduction to the graphics-related managed classes.

Управляемый код GDI+ About GDI+ Managed Code
Предоставляет сведения об управляемых классах GDI+. Provides information about the managed GDI+ classes.

Использование управляемых графических классов Using Managed Graphics Classes
Демонстрирует выполнение различных задач с помощью управляемых классов GDI+. Demonstrates how to complete a variety of tasks using the GDI+ managed classes.

Справочник Reference

System.Drawing
Предоставляет доступ к основным графическим функциям GDI+. Provides access to GDI+ basic graphics functionality.

System.Drawing.Drawing2D
Расширенные функциональные возможности для создания двухмерной и векторной графики. Provides advanced two-dimensional and vector graphics functionality.

System.Drawing.Imaging
Предоставляет расширенные графические функции GDI+. Provides advanced GDI+ imaging functionality.

System.Drawing.Text
Предоставляет расширенный набор типографических функций GDI+. Provides advanced GDI+ typography functionality. Классы в этом пространстве имен позволяют создавать и использовать коллекции шрифтов. The classes in this namespace can be used to create and use collections of fonts.

System.Drawing.Printing
Функции печати. Provides printing functionality.

Рисование и отрисовка пользовательского элемента управления Custom Control Painting and Rendering
Подробные сведения о способах написания кода для рисования элементов управления. Details how to provide code for painting controls.

Drawing in Windows.Forms

I’ve got a simple Windows.Forms Form.

I want to fill the pictureBox1 with color Color.Aqua and draw a rectangle.

However nothing is drown untill I move the Form.

How can I force everything to be drawn without moving the Form?

3 Answers 3

You must subscribe to Paint event of your picturebox and put your drawing code there,something like this:

This event is raised everytime the control needs to be redrawn, so you don’t need that Timer trick or calling Invalidate

60 FPS). Can’t do that with just handling items in pictureBox.Paint() . – CoolBots Feb 8 ’17 at 17:06

I see four problems:

  1. The Invalidate() method is called for the form. This should invalidate the PictureBox, but you can do better by just invalidating the PictureBox directly.
  2. You are drawing the bitmap, but not updating the Image property of the PictureBox.
  3. One millisecond intervals will kill you. 50 to 100 is much more reasonable, and anything less than 17 is probably faster than the refresh rate of your monitor.
  4. The whole the thing with the separate graphics is extra and not needed. The pictureBox has it’s own graphics context, and you do better using that.

Put it all together, and you get this:

You don’t need the Invalidate() call at all, since you’re drawing to a buffer ( Bitmap ). Just set the bitmap to pictureBox1.Image property:

Not the answer you’re looking for? Browse other questions tagged c# .net winforms or ask your own question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Оцените статью