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

Управляемый интерфейс для кривых

У замкнутых кривых есть внутренняя область, которую можно залить с использованием кисти. Класс Graphics интерфейса GDI+ содержит следующие методы для заливки замкнутых фигур и кривых: FillRectangle (прямые линии), FillEllipse (прямоугольники), FillPie (эллипсы), FillPolygon (многоугольники), FillClosedCurve (дуги), FillPath (фундаментальные сплайны) и FillRegion (сплайны Безье). При вызове одного из этих методов необходимо передавать им в качестве аргумента тип кисти (SolidBrush, HatchBrush, TextureBrush, LinearGradientBrush или PathGradientBrush).

Метод FillPie является дополнением к методу DrawArc. Метод DrawArc служит для рисования части контура эллипса, а метод FillPie — для заливки части внутренней области эллипса. В приведенном ниже примере демонстрируется рисование дуги и заливка соответствующей части внутренней области эллипса.

---------

На приведенном ниже рисунке изображена полученная дуга и залитый сектор.

Метод FillClosedCurve является дополнением к методу DrawClosedCurve. Оба метода автоматически замыкают кривую путем соединения конечной и начальной точки. В приведенном ниже примере демонстрируется рисование кривой через точки с координатами (0, 0), (60, 20) и (40, 50). Затем кривая автоматически замыкается путем соединения точки с координатами (40, 50) с начальной точкой с координатами (0, 0), а внутренняя область закрашивается сплошным цветом.

-------------------

The FillPath method fills the interiors of the separate pieces of a path. If a piece of a path doesn't form a closed curve or shape, the FillPath method automatically closes that piece of the path before filling it. The following example draws and fills a path that consists of an arc, a cardinal spline, a string, and a pie:

SolidBrush mySolidBrush = new SolidBrush(Color.Aqua);

GraphicsPath myGraphicsPath = new GraphicsPath();

Point[] myPointArray = {

new Point(15, 20),

new Point(20, 40),

new Point(50, 30)};

FontFamily myFontFamily = new FontFamily("Times New Roman");

PointF myPointF = new PointF(50, 20);

StringFormat myStringFormat = new StringFormat();

myGraphicsPath.AddArc(0, 0, 30, 20, -90, 180);

myGraphicsPath.AddCurve(myPointArray);

myGraphicsPath.AddString("a string in a path", myFontFamily,

0, 24, myPointF, myStringFormat);

myGraphicsPath.AddPie(230, 10, 40, 40, 40, 110);

myGraphics.FillPath(mySolidBrush, myGraphicsPath);

myGraphics.DrawPath(myPen, myGraphicsPath);

The following illustration shows the path with and without the solid fill. Note that the text in the string is outlined, but not filled, by the DrawPath method. It is the FillPath method that paints the interiors of the characters in the string.

Метод FillPath заливает внутренние области различных частей контура. Если часть контура не образует замкнутую кривую, метод FillPath автоматически замыкает эту часть контура перед началом заливки. В приведенном ниже примере демонстрируются рисование и заливка контура, состоящего из дуги, фундаментального сплайна, строки и сектора.

---------

На приведенном ниже рисунке изображен контур, залитый с использованием сплошного цвета, и вариант такого контура без заливки. Обратите внимание, что метод DrawPath отображает текст строки в виде контуров символов, но не закрашивает эти контуры. Внутренние области знаков строки закрашиваются методом FillPath.

Regions in GDI+

A region is a portion of the display area of an output device. Regions can be simple (a single rectangle) or complex (a combination of polygons and closed curves). The following illustration shows two regions: one constructed from a rectangle, and the other constructed from a path.

Using Regions

Regions are often used for clipping and hit testing. Clipping involves restricting drawing to a certain region of the display area, usually the portion that needs to be updated. Hit testing involves checking to determine whether the cursor is in a certain region of the screen when a mouse button is pressed.

You can construct a region from a rectangle or a path. You can also create complex regions by combining existing regions. The Region class provides the following methods for combining regions: Intersect, Union, Xor, Exclude, and Complement.

The intersection of two regions is the set of all points belonging to both regions. The union is the set of all points belonging to one or the other or both regions. The complement of a region is the set of all points that are not in the region. The following illustration shows the intersection and union of the two regions shown in the preceding illustration.

The Xor method, applied to a pair of regions, produces a region that contains all points that belong to one region or the other, but not both. The Exclude method, applied to a pair of regions, produces a region that contains all points in the first region that are not in the second region. The following illustration shows the regions that result from applying the Xor and Exclude methods to the two regions shown at the beginning of this topic.

To fill a region, you need a Graphics object, a Brush object, and a Region object. The Graphics object provides the FillRegion method, and the Brush object stores attributes of the fill, such as color or pattern. The following example fills a region with a solid color.

myGraphics.FillRegion(mySolidBrush, myRegion);

Области в GDI+

Область — это часть зоны, отображаемой устройством вывода. Области могут быть как простыми (один прямоугольник), так и сложными (набор многоугольников и замкнутых кривых). На приведенном ниже рисунке изображены две области: одна из них образована прямоугольником, а другая образована контуром.

-------