Draw rectangle c windows

Drawing Context. Draw Rectangle Метод

Определение

Рисует прямоугольник. Draws a rectangle.

Перегрузки

Рисует прямоугольник заданными Brush и Pen. Draws a rectangle with the specified Brush and Pen. И перо, и кисть могут одновременно иметь значение null . The pen and the brush can be null .

Рисует прямоугольник заданными Brush и Pen и применяет заданные часы анимации. Draws a rectangle with the specified Brush and Pen and applies the specified animation clocks.

DrawRectangle(Brush, Pen, Rect)

Рисует прямоугольник заданными Brush и Pen. Draws a rectangle with the specified Brush and Pen. И перо, и кисть могут одновременно иметь значение null . The pen and the brush can be null .

Параметры

Кисть для рисования прямоугольника. The brush with which to fill the rectangle. Этот параметр является необязательным и может иметь значение null . This is optional, and can be null . Если в качестве кисти задано значение null , заливка не рисуется. If the brush is null , no fill is drawn.

Перо для обводки прямоугольника. The pen with which to stroke the rectangle. Этот параметр является необязательным и может иметь значение null . This is optional, and can be null . Если в качестве пера задано значение null , штриховка не рисуется. If the pen is null , no stroke is drawn.

Рисуемый прямоугольник. The rectangle to draw.

Комментарии

Кисть и перо могут быть оба null . The brush and the pen can both be null . Если кисть имеет значение null , то заливка не выполняется. If the brush is null , then no fill is performed. Если перо имеет значение null , штрих не выполняется. If the pen is null , then no stroke is performed. Если используется и перо, и кисть null , то Рисование не отображается. If both the pen and the brush are null , then the drawing is not visible.

Применяется к

DrawRectangle(Brush, Pen, Rect, AnimationClock)

Рисует прямоугольник заданными Brush и Pen и применяет заданные часы анимации. Draws a rectangle with the specified Brush and Pen and applies the specified animation clocks.

Параметры

Кисть для рисования прямоугольника. The brush with which to fill the rectangle. Этот параметр является необязательным и может иметь значение null . This is optional, and can be null . Если в качестве кисти задано значение null , заливка не рисуется. If the brush is null , no fill is drawn.

Перо для обводки прямоугольника. The pen with which to stroke the rectangle. Этот параметр является необязательным и может иметь значение null . This is optional, and can be null . Если в качестве пера задано значение null , штриховка не рисуется. If the pen is null , no stroke is drawn.

Рисуемый прямоугольник. The rectangle to draw.

Часы, с использованием которых следует анимировать размер и измерения прямоугольника, или null , чтобы анимация не выполнялась. The clock with which to animate the rectangle’s size and dimensions, or null for no animation. Эти часы должны быть созданы из AnimationTimeline, способного анимировать объекты Rect. This clock must be created from an AnimationTimeline that can animate Rect objects.

Комментарии

Кисть и перо могут быть оба null . The brush and the pen can both be null . Если кисть имеет значение null , то заливка не выполняется. If the brush is null , then no fill is performed. Если перо имеет значение null , необходимо не выполняется. If the pen is null , then no stoke is performed. Если используется и перо, и кисть null , то Рисование не отображается. If both the pen and the brush are null , then the drawing is not visible.

Читайте также:  Windows user history files

Rectangle Структура

Определение

Содержит набор из четырех целых чисел, определяющих расположение и размер прямоугольника. Stores a set of four integers that represent the location and size of a rectangle.

Примеры

В следующем примере демонстрируется рисование прямоугольника с верхним левым углом в точке (10, 10). The following example draws a rectangle with its upper-left corner at (10, 10). Ширина прямоугольника равна 100 и высоте 50. The rectangle has a width of 100 and a height of 50. Второй аргумент, передаваемый Pen конструктору, указывает, что ширина пера равна 5 пикселам. The second argument passed to the Pen constructor indicates that the pen width is 5 pixels.

При прорисовке прямоугольника перо центрируется по границе прямоугольника. When the rectangle is drawn, the pen is centered on the rectangle’s boundary. Так как ширина пера равна 5, стороны прямоугольника выводятся в ширину 5 пикселей, то есть 1 пиксель рисуется на границе, 2 пиксела нарисованы внутри, а 2 пиксела — снаружи. Because the pen width is 5, the sides of the rectangle are drawn 5 pixels wide, such that 1 pixel is drawn on the boundary itself, 2 pixels are drawn on the inside, and 2 pixels are drawn on the outside. Дополнительные сведения о выравнивании пера см. в разделе как задать ширину и выравнивание пера. For more details on pen alignment, see How to: Set Pen Width and Alignment.

На следующем рисунке показан итоговый прямоугольник. The following illustration shows the resulting rectangle. Пунктирные линии показывают, где будет нарисован прямоугольник, если толщина пера была равна одному пикселю. The dotted lines show where the rectangle would have been drawn if the pen width had been one pixel. Увеличенное представление верхнего левого угла прямоугольника показывает, что толстые черные линии центрируются по пунктирным линиям. The enlarged view of the upper-left corner of the rectangle shows that the thick black lines are centered on those dotted lines.

Пример предназначен для использования с Windows Forms и требует PaintEventArgs e , что является параметром Paint обработчика событий. The example is designed for use with Windows Forms, and it requires PaintEventArgs e , which is a parameter of the Paint event handler.

Комментарии

Прямоугольник определяется по его Width , и левому Height верхнему углу, представленному Location свойством. A rectangle is defined by its Width, Height, and upper-left corner represented by the Location property.

Для рисования прямоугольников необходим Graphics объект и Pen объект. To draw rectangles, you need a Graphics object and a Pen object. GraphicsОбъект предоставляет DrawRectangle метод, а Pen объект сохраняет функции линии, такие как цвет и ширина. The Graphics object provides the DrawRectangle method, and the Pen object stores features of the line, such as color and width. Единицы, которые рисует прямоугольник, определяются PageUnit PageScale свойствами и графического объекта, используемого для рисования. The units the rectangle is drawn in is determined by the PageUnit and PageScale properties of the graphics object used for drawing. Единицей по умолчанию являются пиксели. The default unit is pixels.

Чтобы нарисовать Rectangle заливку цветом, необходим Graphics объект и объект, производный от, Brush например SolidBrush или LinearGradientBrush . To draw a Rectangle filled with color, you need a Graphics object and an object derived from Brush such as SolidBrush or LinearGradientBrush. GraphicsОбъект предоставляет FillRectangle метод, а Brush объект предоставляет сведения о цвете и заполнении. The Graphics object provides the FillRectangle method and the Brush object provides the color and fill information.

Для более сложных фигур используйте Region объект. For more advanced shapes, use a Region object.

Конструкторы

Инициализирует новый экземпляр класса Rectangle заданным расположением и размером. Initializes a new instance of the Rectangle class with the specified location and size.

Инициализирует новый экземпляр класса Rectangle заданным расположением и размером. Initializes a new instance of the Rectangle class with the specified location and size.

Представляет структуру Rectangle, свойства которой не инициализированы. Represents a Rectangle structure with its properties left uninitialized.

Читайте также:  Кто делает установку windows

Свойства

Возвращает координату по оси Y, являющуюся суммой значений свойств Y и Height данной структуры Rectangle. Gets the y-coordinate that is the sum of the Y and Height property values of this Rectangle structure.

Возвращает или задает высоту в структуре Rectangle. Gets or sets the height of this Rectangle structure.

Проверяет, все ли числовые свойства этого прямоугольника Rectangle имеют нулевые значения. Tests whether all numeric properties of this Rectangle have values of zero.

Возвращает координату по оси X левого края структуры Rectangle. Gets the x-coordinate of the left edge of this Rectangle structure.

Возвращает или задает координаты левого верхнего угла структуры Rectangle. Gets or sets the coordinates of the upper-left corner of this Rectangle structure.

Возвращает координату по оси X, являющуюся суммой значений свойств X и Width данной структуры Rectangle. Gets the x-coordinate that is the sum of X and Width property values of this Rectangle structure.

Возвращает или задает размер этого объекта Rectangle. Gets or sets the size of this Rectangle.

Возвращает координату по оси Y верхнего края структуры Rectangle. Gets the y-coordinate of the top edge of this Rectangle structure.

Возвращает или задает ширину структуры Rectangle. Gets or sets the width of this Rectangle structure.

Возвращает или задает координату по оси X левого верхнего угла структуры Rectangle. Gets or sets the x-coordinate of the upper-left corner of this Rectangle structure.

Возвращает или задает координату по оси Y левого верхнего угла структуры Rectangle. Gets or sets the y-coordinate of the upper-left corner of this Rectangle structure.

Методы

Преобразует указанную структуру RectangleF в структуру Rectangle, округляя значения RectangleF до ближайшего большего целого числа. Converts the specified RectangleF structure to a Rectangle structure by rounding the RectangleF values to the next higher integer values.

Определяет, содержится ли заданная точка в структуре Rectangle. Determines if the specified point is contained within this Rectangle structure.

Определяет, содержится ли заданная точка в структуре Rectangle. Determines if the specified point is contained within this Rectangle structure.

Определяет, содержится ли вся прямоугольная область, представленная параметром rect , в структуре Rectangle. Determines if the rectangular region represented by rect is entirely contained within this Rectangle structure.

Проверяет, является ли obj структурой Rectangle с таким же расположением и размером, что и структура Rectangle. Tests whether obj is a Rectangle structure with the same location and size of this Rectangle structure.

Указывает, равен ли текущий объект другому объекту того же типа. Indicates whether the current object is equal to another object of the same type.

Создает структуру Rectangle с заданным положением краев. Creates a Rectangle structure with the specified edge locations.

Возвращает хэш-код данной структуры Rectangle. Returns the hash code for this Rectangle structure. Дополнительные сведения об использовании хэш-кодов см. в разделе GetHashCode(). For information about the use of hash codes, see GetHashCode() .

Увеличивает данный объект Rectangle на заданную величину. Enlarges this Rectangle by the specified amount.

Создает и возвращает увеличенную копию заданной структуры Rectangle. Creates and returns an enlarged copy of the specified Rectangle structure. Копия увеличивается на заданную величину. The copy is enlarged by the specified amount. Исходная структура Rectangle остается без изменений. The original Rectangle structure remains unmodified.

Увеличивает данный объект Rectangle на заданную величину. Enlarges this Rectangle by the specified amount.

Заменяет данный объект Rectangle его пересечением с указанным прямоугольником Rectangle. Replaces this Rectangle with the intersection of itself and the specified Rectangle.

Возвращает третью структуру Rectangle, представляющую собой пересечение двух других структур Rectangle. Returns a third Rectangle structure that represents the intersection of two other Rectangle structures. Если пересечение отсутствует, возвращается пустая структура Rectangle. If there is no intersection, an empty Rectangle is returned.

Определяет, пересекается ли данный прямоугольник с прямоугольником rect . Determines if this rectangle intersects with rect .

Читайте также:  Rivatuner как отключить windows 10

Изменяет положение этого прямоугольника на указанную величину. Adjusts the location of this rectangle by the specified amount.

Изменяет положение этого прямоугольника на указанную величину. Adjusts the location of this rectangle by the specified amount.

Преобразует указанный RectangleF в Rectangle, округляя значения RectangleF до ближайших целых чисел. Converts the specified RectangleF to a Rectangle by rounding the RectangleF values to the nearest integer values.

Преобразует атрибуты этого прямоугольника Rectangle в удобную для восприятия строку. Converts the attributes of this Rectangle to a human-readable string.

Преобразует указанный объект RectangleF в Rectangle путем усечения значений RectangleF. Converts the specified RectangleF to a Rectangle by truncating the RectangleF values.

Возвращает структуру Rectangle, содержащую объединение двух структур Rectangle. Gets a Rectangle structure that contains the union of two Rectangle structures.

Операторы

Проверяет, имеют ли две структуры Rectangle одинаковое положение и размер. Tests whether two Rectangle structures have equal location and size.

Проверяет, различаются ли две структуры Rectangle по положению или размеру. Tests whether two Rectangle structures differ in location or size.

Graphics. Draw Rectangle Метод

Определение

Рисует прямоугольник, определяемый парой координат, шириной и высотой. Draws a rectangle specified by a coordinate pair, a width, and a height.

Перегрузки

Рисует прямоугольник, определяемый структурой Rectangle. Draws a rectangle specified by a Rectangle structure.

Рисует прямоугольник, определяемый парой координат, шириной и высотой. Draws a rectangle specified by a coordinate pair, a width, and a height.

Рисует прямоугольник, определяемый парой координат, шириной и высотой. Draws a rectangle specified by a coordinate pair, a width, and a height.

DrawRectangle(Pen, Rectangle)

Рисует прямоугольник, определяемый структурой Rectangle. Draws a rectangle specified by a Rectangle structure.

Параметры

Структура Pen, определяющая цвет, ширину и стиль прямоугольника. A Pen that determines the color, width, and style of the rectangle.

Структура Rectangle, представляющая прямоугольник для рисования. A Rectangle structure that represents the rectangle to draw.

Исключения

pen имеет значение null . pen is null .

Примеры

Следующий пример кода предназначен для использования с Windows Forms и требует PaintEventArgs e , что является параметром Paint обработчика событий. The following code example is designed for use with Windows Forms, and it requires PaintEventArgs e , which is a parameter of the Paint event handler. Код выполняет следующие действия. The code performs the following actions:

Создает черное перо. Creates a black pen.

Создает прямоугольник. Creates a rectangle.

Отображает прямоугольник на экране. Draws the rectangle to the screen.

Комментарии

Дополнительные сведения о рисовании RectangleF см. в разделе DrawRectangles(Pen, RectangleF[]) . For information about how to draw a RectangleF, see DrawRectangles(Pen, RectangleF[]).

Применяется к

DrawRectangle(Pen, Int32, Int32, Int32, Int32)

Рисует прямоугольник, определяемый парой координат, шириной и высотой. Draws a rectangle specified by a coordinate pair, a width, and a height.

Параметры

Структура Pen, определяющая цвет, ширину и стиль прямоугольника. Pen that determines the color, width, and style of the rectangle.

Координата X верхнего левого угла прямоугольника для рисования. The x-coordinate of the upper-left corner of the rectangle to draw.

Координата Y верхнего левого угла прямоугольника для рисования. The y-coordinate of the upper-left corner of the rectangle to draw.

Ширина прямоугольника для рисования. Width of the rectangle to draw.

Высота прямоугольника для рисования. Height of the rectangle to draw.

Исключения

pen имеет значение null . pen is null .

Примеры

Следующий пример кода предназначен для использования с Windows Forms и требует PaintEventArgs e , что является параметром Paint обработчика событий. The following code example is designed for use with Windows Forms, and it requires PaintEventArgs e , which is a parameter of the Paint event handler. Код выполняет следующие действия. The code performs the following actions:

Создает черное перо. Creates a black pen.

Создает расположение и размер прямоугольника. Creates the position and size of a rectangle.

Отображает прямоугольник на экране. Draws the rectangle to the screen.

Комментарии

Дополнительные сведения о рисовании RectangleF см. в разделе DrawRectangles(Pen, RectangleF[]) . For information about how to draw a RectangleF, see DrawRectangles(Pen, RectangleF[]).

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