- Объекты Graphics и Drawing в Windows Forms Graphics and Drawing in Windows Forms
- в этом разделе In This Section
- Справочник Reference
- Связанные разделы Related Sections
- 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
- DrawText function (winuser.h)
- Syntax
- Parameters
- Return value
- Remarks
Объекты 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.
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.
DrawText function (winuser.h)
The DrawText function draws formatted text in the specified rectangle. It formats the text according to the specified method (expanding tabs, justifying characters, breaking lines, and so forth).
To specify additional formatting options, use the DrawTextEx function.
Syntax
Parameters
A handle to the device context.
A pointer to the string that specifies the text to be drawn. If the nCount parameter is -1, the string must be null-terminated.
If uFormat includes DT_MODIFYSTRING, the function could add up to four additional characters to this string. The buffer containing the string should be large enough to accommodate these extra characters.
The length, in characters, of the string. If nCount is -1, then the lpchText parameter is assumed to be a pointer to a null-terminated string and DrawText computes the character count automatically.
A pointer to a RECT structure that contains the rectangle (in logical coordinates) in which the text is to be formatted.
The method of formatting the text. This parameter can be one or more of the following values.
Value | Meaning |
---|---|
DT_BOTTOM | Justifies the text to the bottom of the rectangle. This value is used only with the DT_SINGLELINE value. |
DT_CALCRECT | Determines the width and height of the rectangle. If there are multiple lines of text, DrawText uses the width of the rectangle pointed to by the lpRect parameter and extends the base of the rectangle to bound the last line of text. If the largest word is wider than the rectangle, the width is expanded. If the text is less than the width of the rectangle, the width is reduced. If there is only one line of text, DrawText modifies the right side of the rectangle so that it bounds the last character in the line. In either case, DrawText returns the height of the formatted text but does not draw the text. |
DT_CENTER | Centers text horizontally in the rectangle. |
DT_EDITCONTROL | Duplicates the text-displaying characteristics of a multiline edit control. Specifically, the average character width is calculated in the same manner as for an edit control, and the function does not display a partially visible last line. |
DT_END_ELLIPSIS | For displayed text, if the end of a string does not fit in the rectangle, it is truncated and ellipses are added. If a word that is not at the end of the string goes beyond the limits of the rectangle, it is truncated without ellipses. The string is not modified unless the DT_MODIFYSTRING flag is specified. Compare with DT_PATH_ELLIPSIS and DT_WORD_ELLIPSIS. |
DT_EXPANDTABS | Expands tab characters. The default number of characters per tab is eight. The DT_WORD_ELLIPSIS, DT_PATH_ELLIPSIS, and DT_END_ELLIPSIS values cannot be used with the DT_EXPANDTABS value. |
DT_EXTERNALLEADING | Includes the font external leading in line height. Normally, external leading is not included in the height of a line of text. |
DT_HIDEPREFIX | Ignores the ampersand (&) prefix character in the text. The letter that follows will not be underlined, but other mnemonic-prefix characters are still processed. input string: «A&bc&&d» Compare with DT_NOPREFIX and DT_PREFIXONLY. |
DT_INTERNAL | Uses the system font to calculate text metrics. |
DT_LEFT | Aligns text to the left. |
DT_MODIFYSTRING | Modifies the specified string to match the displayed text. This value has no effect unless DT_END_ELLIPSIS or DT_PATH_ELLIPSIS is specified. |
DT_NOCLIP | Draws without clipping. DrawText is somewhat faster when DT_NOCLIP is used. |
DT_NOFULLWIDTHCHARBREAK | Prevents a line break at a DBCS (double-wide character string), so that the line breaking rule is equivalent to SBCS strings. For example, this can be used in Korean windows, for more readability of icon labels. This value has no effect unless DT_WORDBREAK is specified. |
DT_NOPREFIX | Turns off processing of prefix characters. Normally, DrawText interprets the mnemonic-prefix character & as a directive to underscore the character that follows, and the mnemonic-prefix characters && as a directive to print a single &. By specifying DT_NOPREFIX, this processing is turned off. For example, input string: «A&bc&&d» Compare with DT_HIDEPREFIX and DT_PREFIXONLY. |
DT_PATH_ELLIPSIS | For displayed text, replaces characters in the middle of the string with ellipses so that the result fits in the specified rectangle. If the string contains backslash (\\) characters, DT_PATH_ELLIPSIS preserves as much as possible of the text after the last backslash. The string is not modified unless the DT_MODIFYSTRING flag is specified. Compare with DT_END_ELLIPSIS and DT_WORD_ELLIPSIS. |
DT_PREFIXONLY | Draws only an underline at the position of the character following the ampersand (&) prefix character. Does not draw any other characters in the string. For example, input string: «A&bc&&d»n Compare with DT_HIDEPREFIX and DT_NOPREFIX. |
DT_RIGHT | Aligns text to the right. |
DT_RTLREADING | Layout in right-to-left reading order for bidirectional text when the font selected into the hdc is a Hebrew or Arabic font. The default reading order for all text is left-to-right. |
DT_SINGLELINE | Displays text on a single line only. Carriage returns and line feeds do not break the line. |
DT_TABSTOP | Sets tab stops. Bits 15-8 (high-order byte of the low-order word) of the uFormat parameter specify the number of characters for each tab. The default number of characters per tab is eight. The DT_CALCRECT, DT_EXTERNALLEADING, DT_INTERNAL, DT_NOCLIP, and DT_NOPREFIX values cannot be used with the DT_TABSTOP value. |
DT_TOP | Justifies the text to the top of the rectangle. |
DT_VCENTER | Centers text vertically. This value is used only with the DT_SINGLELINE value. |
DT_WORDBREAK | Breaks words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the lpRect parameter. A carriage return-line feed sequence also breaks the line. If this is not specified, output is on one line. |
DT_WORD_ELLIPSIS | Truncates any word that does not fit in the rectangle and adds ellipses. Compare with DT_END_ELLIPSIS and DT_PATH_ELLIPSIS. Return valueIf the function succeeds, the return value is the height of the text in logical units. If DT_VCENTER or DT_BOTTOM is specified, the return value is the offset from lpRect->top to the bottom of the drawn text If the function fails, the return value is zero. RemarksThe DrawText function uses the device context’s selected font, text color, and background color to draw the text. Unless the DT_NOCLIP format is used, DrawText clips the text so that it does not appear outside the specified rectangle. Note that text with significant overhang may be clipped, for example, an initial «W» in the text string or text that is in italics. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is specified. If the selected font is too large for the specified rectangle, the DrawText function does not attempt to substitute a smaller font. The text alignment mode for the device context must include the TA_LEFT, TA_TOP, and TA_NOUPDATECP flags. |