Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Graphics.doc
Скачиваний:
20
Добавлен:
16.11.2019
Размер:
3.1 Mб
Скачать

Компиляция кода

Приведенный выше код выполняется в обработчике события Paint формы, поэтому изображение остается и после перерисовки формы. По этой причине не стоит вызывать методы, связанные с графикой в обработчике события Load, поскольку нарисованные элементы не будут перерисовываться при изменении размера формы, или если форма будет закрыта другой формой.

Using a Pen to Draw Lines and Shapes

Use GDI+ Pen objects to draw line segments, curves, and the outlines of shapes. In this section, line refers to any of these, unless specified to mean only a line segment. Set the properties of a pen to control the color, width, alignment, and style of lines drawn with that pen.

How to: Use a Pen to Draw Lines

To draw lines, you need a Graphics object and a Pen object. The Graphics object provides the DrawLine method, and the Pen object stores features of the line, such as color and width.

Example

The following example draws a line from (20, 10) to (300, 100). The first statement uses the Pen class constructor to create a black pen. The one argument passed to the Pen constructor is a Color object created with the FromArgb method. The values used to create the Color object — (255, 0, 0, 0) — correspond to the alpha, red, green, and blue components of the color. These values define an opaque black pen.

Pen pen = new Pen(Color.FromArgb(255, 0, 0, 0));

e.Graphics.DrawLine(pen, 20, 10, 300, 100);

Compiling the Code

The preceding example is designed for use with Windows Forms, and it requires PaintEventArgse, which is a parameter of the Paint event handler.

Рисование линий и фигур с помощью пера

Используйте для рисования линейных сегментов, кривых, а также контуров различных фигур объекты GDI+ Pen. В данном разделе термин линия относится ко всему вышеперечисленному, если только специально не указывается, что имеется в виду отрезок прямой. Для управления цветом, толщиной, выравниванием и стилем линий, рисуемых пером, устанавливайте значения соответствующих свойств этого соответствующего объекта Pen.

Рисование линий с помощью пера

Чтобы нарисовать линию, нужно создать два объекта: объект Graphics и объект Pen. У объекта Graphics имеется метод DrawLine, а объект Pen предназначен для хранения таких параметров рисуемой линии, как ее ширина и цвет.

Пример

В следующем примере рисуется прямая линия, соединяющая точки (20, 10) и (300, 100). В первой инструкции вызывается конструктор класса Pen и создается перо. Единственный аргумент, передаваемый конструктору Pen, является объектом Color, созданным с помощью метода FromArgb. Значения, используемые при создании объекта Color (255, 0, 0, 0), соответствуют альфа-, красному, зеленому, синему компонентам цвета. Приведенные значения определяют непрозрачное черное перо.

-------

Компиляция кода

Предыдущий пример предназначен для работы с Windows Forms, для него необходим объект PaintEventArgs e, передаваемый в качестве параметра обработчику события Paint.

How to: Use a Pen to Draw Rectangles

To draw rectangles, you need a Graphics object and a Pen object. The Graphics object provides the DrawLine method, and the Pen object stores features of the line, such as color and width.

Example

The following example draws a rectangle with its upper-left corner at (10, 10). The rectangle has a width of 100 and a height of 50. 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. 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.

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.

Pen blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 5);

e.Graphics.DrawRectangle(blackPen, 10, 10, 100, 50);

Compiling the Code

The preceding example is designed for use with Windows Forms, and it requires PaintEventArgse, which is a parameter of the Paint event handler.