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

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

Создайте форму Windows Forms и перейдите к обработчику события Paint этой формы. Вставьте приведенный выше код в обработчик события Paint. Подставьте вместо Texture.jpg имя имеющегося на вашем компьютере файла изображения.

Using a Brush to Fill Shapes

A GDI+ Brush object is used to fill the interior of a closed shape. GDI+ defines several fill styles: solid color, hatch pattern, image texture, and color gradient.

How to: Fill a Shape with a Solid Color

To fill a shape with a solid color, create a SolidBrush object, and then pass that SolidBrush object as an argument to one of the fill methods of the Graphics class. The following example shows how to fill an ellipse with the color red.

Example

In the following code, the SolidBrush constructor takes a Color object as its only argument. The values used by the FromArgb method represent the alpha, red, green, and blue components of the color. Each of these values must be in the range 0 through 255. The first 255 indicates that the color is fully opaque, and the second 255 indicates that the red component is at full intensity. The two zeros indicate that the green and blue components both have an intensity of 0.

The four numbers (0, 0, 100, 60) passed to the FillEllipse method specify the location and size of the bounding rectangle for the ellipse. The rectangle has an upper-left corner of (0, 0), a width of 100, and a height of 60.

SolidBrush solidBrush = new SolidBrush(

Color.FromArgb(255, 255, 0, 0));

e.Graphics.FillEllipse(solidBrush, 0, 0, 100, 60);

Compiling the Code

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

Использование кисти для заливки фигур

Объект GDI+ Brush служит для заливки внутренней области замкнутых фигур. В GDI+ определены следующие стили заливки: сплошной цвет, шаблон штриховки, текстура с изображением и цветовой градиент.

Заливка фигуры сплошным цветом

Чтобы залить фигуру сплошным цветом, создайте объект SolidBrush и передайте его в качестве параметра одному из методов заливки класса Graphics. В следующем примере демонстрируется заливка эллипса сплошным красным цветом.

Пример

В приведенном выше коде конструктор SolidBrush получает в качестве своего единственного параметра объект Color. Значения, используемые методом FromArgb, соответствуют альфа-, красному, зеленому и синему компонентам цвета. Каждое из указанных значений должно лежать в диапазоне от 0 до 255. Первое число 255 указывает, что цвет является абсолютно непрозрачным, а второе число 255 соответствует наибольшей интенсивности красного компонента. Два нуля показывают, что зеленый и синий компоненты оба имеют нулевую интенсивность.

Четыре числа (0, 0, 100, 60), передаваемые методу FillEllipse, определяют положение и размер прямоугольника, ограничивающего рисуемый эллипс. Верхний левый угол прямоугольника располагается в точке (0, 0), ширина прямоугольника равна 100, а высота — 60.

-----

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

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

How to: Fill a Shape with a Hatch Pattern

A hatch pattern is made from two colors: one for the background and one for the lines that form the pattern over the background. To fill a closed shape with a hatch pattern, use a HatchBrush object. The following example demonstrates how to fill an ellipse with a hatch pattern:

Example

The HatchBrush constructor takes three arguments: the hatch style, the color of the hatch line, and the color of the background. The hatch style argument can be any value from the HatchStyle enumeration. There are more than fifty elements in the HatchStyle enumeration; a few of those elements are shown in the following list:

  • Horizontal

  • Vertical

  • ForwardDiagonal

  • BackwardDiagonal

  • Cross

  • DiagonalCross

The following illustration shows the filled ellipse.

HatchBrush hBrush = new HatchBrush(

HatchStyle.Horizontal,

Color.Red,

Color.FromArgb(255, 128, 255, 255));

e.Graphics.FillEllipse(hBrush, 0, 0, 100, 60);

Compiling the Code

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