- Практическое руководство. Рисование текста с использованием GDI How to: Draw Text with GDI
- Пример Example
- Компиляция кода Compiling the Code
- Объекты 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
- Text Renderer. Draw Text Method
- Definition
- Overloads
- Remarks
- DrawText(IDeviceContext, ReadOnlySpan , Font, Point, Color)
- Parameters
- Exceptions
- Applies to
- DrawText(IDeviceContext, String, Font, Rectangle, Color, Color, TextFormatFlags)
- Parameters
- Exceptions
- Examples
- Remarks
- Applies to
- DrawText(IDeviceContext, String, Font, Point, Color, Color, TextFormatFlags)
- Parameters
- Exceptions
- Examples
- Remarks
Практическое руководство. Рисование текста с использованием GDI How to: Draw Text with GDI
С помощью DrawText метода в TextRenderer классе можно получить доступ к ФУНКЦИОНАЛЬНЫМ возможностям GDI для рисования текста в форме или элементе управления. With the DrawText method in the TextRenderer class, you can access GDI functionality for drawing text on a form or control. Визуализация текста GDI обычно обеспечивает лучшую производительность и более точное измерение текста, чем GDI+. GDI text rendering typically offers better performance and more accurate text measuring than GDI+.
DrawTextМетоды TextRenderer класса не поддерживаются для печати. The DrawText methods of the TextRenderer class are not supported for printing. При печати всегда используйте DrawString методы Graphics класса. When printing, always use the DrawString methods of the Graphics class.
Пример Example
В следующем примере кода показано, как нарисовать текст на нескольких строках в прямоугольнике с помощью DrawText метода. The following code example demonstrates how to draw text on multiple lines within a rectangle using the DrawText method.
Для отрисовки текста с помощью TextRenderer класса требуется IDeviceContext , например, Graphics и Font , расположение для рисования текста, а также цвет, в котором он должен быть нарисован. To render text with the TextRenderer class, you need an IDeviceContext, such as a Graphics and a Font, a location to draw the text, and the color in which it should be drawn. При необходимости можно указать форматирование текста с помощью TextFormatFlags перечисления. Optionally, you can specify the text formatting by using the TextFormatFlags enumeration.
Дополнительные сведения о получении Graphics см. в разделе инструкции. Создание графических объектов для рисования. For more information about obtaining a Graphics, see How to: Create Graphics Objects for Drawing. Дополнительные сведения о создании Font см. в разделе как создавать гарнитуры шрифтов и шрифты. For more information about constructing a Font, see How to: Construct Font Families and Fonts.
Компиляция кода Compiling the Code
Приведенный выше пример кода предназначен для использования с Windows Forms и требует PaintEventArgs e , который является параметром PaintEventHandler . The preceding code example is designed for use with Windows Forms, and it requires the PaintEventArgs e , which is a parameter of PaintEventHandler.
Объекты 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:
Text Renderer. Draw Text Method
Definition
Draws the specified text at the specified location, using the specified device context, color, and font.
Overloads
Draws the specified text at the specified location using the specified device context, font, and color.
Draws the specified text within the specified bounds using the specified device context, font, color, back color, and formatting instructions.
Draws the specified text at the specified location using the specified device context, font, color, back color, and formatting instructions.
Draws the specified text at the specified location using the specified device context, font, color, back color, and formatting instructions.
Draws the specified text within the specified bounds using the specified device context, font, color, and formatting instructions.
Draws the specified text within the specified bounds using the specified device context, font, color, and back color.
Draws the specified text at the specified location using the specified device context, font, color, and formatting instructions.
Draws the specified text at the specified location, using the specified device context, font, color, and back color.
Draws the specified text within the specified bounds using the specified device context, font, color, back color, and formatting instructions.
Draws the specified text within the specified bounds using the specified device context, font, color, and back color.
Draws the specified text at the specified location using the specified device context, font, color, and formatting instructions.
Draws the specified text at the specified location, using the specified device context, font, color, and back color.
Draws the specified text within the specified bounds, using the specified device context, font, and color.
Draws the specified text at the specified location using the specified device context, font, and color.
Draws the specified text within the specified bounds, using the specified device context, font, and color.
Draws the specified text within the specified bounds using the specified device context, font, color, and formatting instructions.
Remarks
The text rendering offered by the TextRenderer class is based on GDI text rendering and is not supported for printing from Windows Forms. Instead, use the DrawString methods of the Graphics class.
DrawText(IDeviceContext, ReadOnlySpan , Font, Point, Color)
Draws the specified text at the specified location using the specified device context, font, and color.
Parameters
The device context in which to draw the text.
The text to draw.
The Font to apply to the drawn text.
The Point that represents the upper-left corner of the drawn text.
The Color to apply to the drawn text.
Exceptions
Applies to
DrawText(IDeviceContext, String, Font, Rectangle, Color, Color, TextFormatFlags)
Draws the specified text within the specified bounds using the specified device context, font, color, back color, and formatting instructions.
Parameters
The device context in which to draw the text.
The text to draw.
The Font to apply to the drawn text.
The Rectangle that represents the bounds of the text.
The Color to apply to the text.
The Color to apply to the area represented by bounds .
A bitwise combination of the TextFormatFlags values.
Exceptions
Examples
The following code example demonstrates how to use the DrawText method. To run this example, paste the code into a Windows Form and call RenderText8 from the form’s Paint event handler, passing e as PaintEventArgs.
Remarks
The backcolor parameter is applied to the area within the bounds parameter . If font , forecolor or backcolor is null or Empty, respectively; the DrawText method will draw the text in the font or color currently selected in the device context specified by dc . If forecolor is Transparent, the text will not be drawn.
You can manipulate how the text is drawn by using one of the DrawText overloads that takes a TextFormatFlags parameter. For example, the default behavior of the TextRenderer is to add padding to the bounding rectangle of the drawn text to accommodate overhanging glyphs. If you need to draw a line of text without these extra spaces you should use the versions of DrawText and MeasureText that take a Size and TextFormatFlags parameter. For an example, see MeasureText(IDeviceContext, String, Font, Size, TextFormatFlags).
The text rendering offered by the TextRenderer class is based on GDI text rendering and is not supported for printing from Windows Forms. Instead, use the DrawString methods of the Graphics class.
The TextRenderer does not support adding tab stops to drawn text, although you can expand existing tab stops using the ExpandTabs flag.
Applies to
DrawText(IDeviceContext, String, Font, Point, Color, Color, TextFormatFlags)
Draws the specified text at the specified location using the specified device context, font, color, back color, and formatting instructions.
Parameters
The device context in which to draw the text.
The text to draw.
The Font to apply to the drawn text.
The Point that represents the upper-left corner of the drawn text.
The Color to apply to the text.
The Color to apply to the background area of the drawn text.
A bitwise combination of the TextFormatFlags values.
Exceptions
Examples
The following code example demonstrates how to use the DrawText method. To run this example, paste the code into a Windows Form and call RenderText7 from the form’s Paint event handler, passing e as PaintEventArgs.
Remarks
The backcolor parameter is applied the rectangular area containing the drawn text. If font or forecolor is null or Empty, respectively; the DrawText method will draw the text in the font or color currently selected in the device context specified by dc . If forecolor is Transparent, the text will not be drawn.
You can manipulate how the text is drawn by using one of the DrawText overloads that takes a TextFormatFlags parameter. For example, the default behavior of the TextRenderer is to add padding to the bounding rectangle of the drawn text to accommodate overhanging glyphs. If you need to draw a line of text without these extra spaces you should use the versions of DrawText and MeasureText that take a Size and TextFormatFlags parameter. For an example, see MeasureText(IDeviceContext, String, Font, Size, TextFormatFlags).
The text rendering offered by the TextRenderer class is based on GDI text rendering and is not supported for printing from Windows Forms. Instead, use the DrawString methods of the Graphics class.
The TextRenderer does not support adding tab stops to drawn text, although you can expand existing tab stops using the ExpandTabs flag.
The DrawText methods that specify a Point as the upper-left corner of the drawn text do not render correctly on Windows 2000. If your application is intended for use on machines running Windows 2000, you should use one of the DrawText methods that specify a Rectangle for the bounds of the drawn text.