- Объекты Graphics и Drawing в Windows Forms Graphics and Drawing in Windows Forms
- в этом разделе In This Section
- Справочник Reference
- Связанные разделы Related Sections
- Практическое руководство. Создание графических объектов для рисования How to: Create Graphics Objects for Drawing
- Создание графического объекта Creating a Graphics Object
- Создание графического объекта To create a graphics object
- PaintEventArgs в обработчике событий Paint PaintEventArgs in the Paint Event Handler
- Получение ссылки на объект Graphics из PaintEventArgs в событии Paint To obtain a reference to a Graphics object from the PaintEventArgs in the Paint event
- Метод CreateGraphics CreateGraphics Method
- Создание графического объекта с помощью метода CreateGraphics To create a Graphics object with the CreateGraphics method
- Создание из объекта Image Create from an Image Object
- Создание графического объекта из изображения To create a Graphics object from an Image
- Рисование фигур и изображений и управление ими Drawing and Manipulating Shapes and Images
- Использование созданного объекта Graphics To use the Graphics object you have created
- Using DrawImage in winform
- 1 Answer 1
- Практическое руководство. Отрисовка изображений с использованием GDI+ How to: Render Images with GDI+
- Вывод изображения с помощью GDI+ To render an image with GDI+
Объекты 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.
в этом разделе 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.
Связанные разделы Related Sections
Рисование и отрисовка пользовательского элемента управления Custom Control Painting and Rendering
Подробные сведения о способах написания кода для рисования элементов управления. Details how to provide code for painting controls.
Практическое руководство. Создание графических объектов для рисования How to: Create Graphics Objects for Drawing
Прежде чем рисовать линии и фигуры, отображать текст или отображать изображения и управлять ими с помощью GDI+, необходимо создать Graphics объект. Before you can draw lines and shapes, render text, or display and manipulate images with GDI+, you need to create a Graphics object. GraphicsОбъект представляет поверхность рисования GDI+, а — объект, используемый для создания графических изображений. 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:
Создание Graphics объекта. Creating a Graphics object.
Использование Graphics объекта для рисования линий и фигур, отображения текста или отображения изображений и управления ими. 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
Получение ссылки на графический объект в составе PaintEventArgs Paint события формы или элемента управления. 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. Аналогично, объект Graphics можно также получить как свойство объекта PrintPageEventArgs при обработке PrintPage события для PrintDocument . Similarly, you can also obtain a graphics object as a property of the PrintPageEventArgs when handling the PrintPage event for a PrintDocument.
Вызовите CreateGraphics метод элемента управления или формы, чтобы получить ссылку на Graphics объект, представляющий поверхность рисования этого элемента управления или формы. 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.
Создайте Graphics объект из любого объекта, наследующего от Image . 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 в обработчике событий Paint PaintEventArgs in the Paint Event Handler
При программировании PaintEventHandler для элементов управления или PrintPage для PrintDocument объект Graphics предоставляется как одно из свойств PaintEventArgs или PrintPageEventArgs . 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.
Получение ссылки на объект Graphics из PaintEventArgs в событии Paint To obtain a reference to a Graphics object from the PaintEventArgs in the Paint event
Объявите Graphics объект. Declare the Graphics object.
Назначьте переменную для ссылки на Graphics объект, передаваемый как часть PaintEventArgs . Assign the variable to refer to the Graphics object passed as part of the PaintEventArgs.
Вставка кода для заполнения формы или элемента управления. Insert code to paint the form or control.
В следующем примере показано, как ссылаться на Graphics объект из PaintEventArgs в Paint событии. The following example shows how to reference a Graphics object from the PaintEventArgs in the Paint event:
Метод CreateGraphics CreateGraphics Method
Можно также использовать CreateGraphics метод элемента управления или формы для получения ссылки на Graphics объект, представляющий поверхность рисования этого элемента управления или формы. 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.
Создание графического объекта с помощью метода CreateGraphics To create a Graphics object with the CreateGraphics method
Вызовите CreateGraphics метод формы или элемента управления, для которого требуется отобразить графические объекты. Call the CreateGraphics method of the form or control upon which you want to render graphics.
Создание из объекта Image Create from an Image Object
Кроме того, можно создать графический объект из любого объекта, производного от Image класса. Additionally, you can create a graphics object from any object that derives from the Image class.
Создание графического объекта из изображения To create a Graphics object from an Image
Вызовите Graphics.FromImage метод, указав имя переменной изображения, из которой нужно создать Graphics объект. Call the Graphics.FromImage method, supplying the name of the Image variable from which you want to create a Graphics object.
В следующем примере показано, как использовать Bitmap объект: The following example shows how to use a Bitmap object:
Создавать объекты можно только Graphics из неиндексированных BMP-файлов, таких как 16-разрядные, 24-разрядные и 32-битовые BMP. You can only create Graphics objects from nonindexed .bmp files, such as 16-bit, 24-bit, and 32-bit .bmp files. Каждый пиксель неиндексированных BMP-файлов содержит цвет, в отличие от пикселов индексированных BMP-файлов, которые содержат индекс для таблицы цветов. 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
После создания Graphics объект может использоваться для рисования линий и фигур, отображения текста или отображения изображений и управления ими. After it is created, a Graphics object may be used to draw lines and shapes, render text, or display and manipulate images. Объекты Principal, используемые с Graphics объектом: The principal objects that are used with the Graphics object are:
PenКласс, используемый для рисования линий, структурирования фигур или визуализации других геометрических представлений. The Pen class—Used for drawing lines, outlining shapes, or rendering other geometric representations.
BrushКласс, используемый для заливки областей графических объектов, таких как заполненные фигуры, изображения или текст. The Brush class—Used for filling areas of graphics, such as filled shapes, images, or text.
FontКласс — содержит описание фигур, используемых при отрисовке текста. The Font class—Provides a description of what shapes to use when rendering text.
ColorСтруктура — представляет различные отображаемые цвета. The Color structure—Represents the different colors to display.
Использование созданного объекта Graphics 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:
Using DrawImage in winform
I am trying to use DrawImage in winform, which draws the specified portion of the specified Image at the specified location and with the specified size. But I am getting certain errors.
The following code snippet taken from here, performs the following:
1- Creates an image from a JPEG file SampImag.jpg in the folder of the example.
2- Creates points that define a parallelogram in which to draw the image.
3- Creates a rectangle to select the portion of the image to draw.
4- Sets the graphics drawing unit to pixel.
5- Draws the image to the screen.
To use this code snippet in my application, I created a simple winform application. In the form I added a button. On button click I want that the following code to execute:
In the application that I created, I got the following lines for the button:
So I am putting the code inside this event, as shown below:
How do I get rid of the error?
I have put system.drawing.dll in the folder where my form1.h is present.
Following is the complete code:
1 Answer 1
Like the compiler said: ‘Graphics‘: is not a member of ‘System::EventArgs‘. The only Event Arguments that have a Graphics object is the PaintEventArgs, which you will only get on Paint and PaintBackground.
Now, since you want to draw the image on the button click event, you will have to create the graphics object for the surface area on which you want to draw the image.
Based on the provided code I’m guessing that you want to draw the image directly to the form. You can create the graphics object by the forms handle, like this:
and simply replace e->Graphics with graphicsInstance to get this call:
More details on the painting itself: As you could see in the article that you have provided, they have just posted the method and conveniently passed the PaintEventArgs as an argument, this is a typical pattern used when overriding the OnPaint and OnPaintBackground to reduce clutter in the paint event code. So just make sure to pass the graphics object from either of the two paint events to your helper method, or if necessary create you own with the method above (Explore the Graphics type a little bit, you will see that you can create it from multiple sources, not just the form’s handle). You can find a nice article on code project with some Theory Crafting around drawing in WinFroms here: link
Практическое руководство. Отрисовка изображений с использованием GDI+ How to: Render Images with GDI+
GDI+ можно использовать для отрисовки изображений, которые существуют как файлы в приложениях. You can use GDI+ to render images that exist as files in your applications. Для этого создается новый объект Image класса (например Bitmap ,), создается Graphics объект, ссылающийся на область рисования, которую вы хотите использовать, и вызывается DrawImage метод Graphics объекта. You do this by creating a new object of an Image class (such as Bitmap), creating a Graphics object that refers to the drawing surface you want to use, and calling the DrawImage method of the Graphics object. Изображение будет выведено на поверхность для рисования, представленную классом Graphics. The image will be painted onto the drawing surface represented by the graphics class. Редактор изображений можно использовать для создания и редактирования файлов изображений во время разработки и их отображения с помощью GDI+ во время выполнения. You can use the Image Editor to create and edit image files at design time, and render them with GDI+ at run time. Дополнительные сведения см. в разделе Редактор изображений для значков. For more information, see Image Editor for Icons.
Вывод изображения с помощью GDI+ To render an image with GDI+
Создайте объект, представляющий изображение, которое необходимо отобразить. Create an object representing the image you want to display. Этот объект должен быть членом класса, наследуемого от Image , такого как Bitmap или Metafile . This object must be a member of a class that inherits from Image, such as Bitmap or Metafile. Пример: An example is shown:
Создайте Graphics объект, представляющий поверхность рисования, которую вы хотите использовать. Create a Graphics object that represents the drawing surface you want to use. Дополнительные сведения см. в разделе Практическое руководство. Создание графических объектов для рисования. For more information, see How to: Create Graphics Objects for Drawing.
Вызовите DrawImage объект Graphics, чтобы отобразить изображение. Call the DrawImage of your graphics object to render the image. Необходимо указать как само выводимое изображение, так и координаты вывода. You must specify both the image to be drawn, and the coordinates where it is to be drawn.