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

Область обрезки

Объект Graphics поддерживает область обрезки, которая применяется для всех объектов, отображаемых объектом Graphics. Для установки границ области обрезки служит метод SetClip.

В следующем примере создается область в форме креста, являющаяся объединением двух прямоугольников. Эта область назначается областью обрезки для объекта Graphics. Затем в коде рисуются две линии, ограниченные внутренней частью области обрезки.

-------

Обрезанные линии показаны на следующем рисунке.

Using Nested Graphics Containers

GDI+ provides containers that you can use to temporarily replace or augment part of the state in a Graphics object. You create a container by calling the BeginContainer method of a Graphics object. You can call BeginContainer repeatedly to form nested containers. Each call to BeginContainer must be paired with a call to EndContainer.

Transformations in Nested Containers

The following example creates a Graphics object and a container within that Graphics object. The world transformation of the Graphics object is a translation 100 units in the x direction and 80 units in the y direction. The world transformation of the container is a 30-degree rotation. The code makes the call DrawRectangle(pen, -60, -30, 120, 60) twice. The first call to DrawRectangle is inside the container; that is, the call is in between the calls to BeginContainer and EndContainer. The second call to DrawRectangle is after the call to EndContainer.

Graphics graphics = e.Graphics;

Pen pen = new Pen(Color.Red);

GraphicsContainer graphicsContainer;

graphics.FillRectangle(Brushes.Black, 100, 80, 3, 3);

graphics.TranslateTransform(100, 80);

graphicsContainer = graphics.BeginContainer();

graphics.RotateTransform(30);

graphics.DrawRectangle(pen, -60, -30, 120, 60);

graphics.EndContainer(graphicsContainer);

graphics.DrawRectangle(pen, -60, -30, 120, 60);

In the preceding code, the rectangle drawn from inside the container is transformed first by the world transformation of the container (rotation) and then by the world transformation of the Graphics object (translation). The rectangle drawn from outside the container is transformed only by the world transformation of the Graphics object (translation). The following illustration shows the two rectangles.

Использование вложенных графических контейнеров

Интерфейс GDI+ предоставляет контейнеры, которые можно использовать, чтобы временно заменить или дополнить некоторую составляющую состояния объекта Graphics. Чтобы создать контейнер, можно вызвать метод BeginContainer объекта Graphics. Для создания вложенных контейнеров можно многократно вызывать метод BeginContainer. Каждому вызову метода BeginContainer должен соответствовать вызов метода EndContainer.

Преобразования во вложенных контейнерах

В приведенном ниже примере создаются объект Graphics и контейнер внутри этого объекта Graphics. Объемным преобразованием объекта Graphics является сдвиг на 100 единиц в направлении оси x и на 80 единиц в направлении оси y. Объемным преобразованием контейнера является поворот на 30 градусов. Код осуществляет вызов метода DrawRectangle(pen, -60, -30, 120, 60) дважды. Первый вызов DrawRectangle осуществляется внутри контейнера. Это значит, что он происходит между вызовами BeginContainer и EndContainer. Второй вызов DrawRectangle происходит после вызова EndContainer.

-----

В приведенном выше коде к прямоугольнику, рисуемому внутри контейнера, применяется сначала объемное преобразование контейнера (поворот), а затем объемное преобразование объекта Graphics (сдвиг). К прямоугольнику, рисуемому вне контейнера, применяется только объемное преобразование объекта Graphics (сдвиг). Два нарисованных прямоугольника показаны на следующем рисунке.

Clipping in Nested Containers

The following example demonstrates how nested containers handle clipping regions. The code creates a Graphics object and a container within that Graphics object. The clipping region of the Graphics object is a rectangle, and the clipping region of the container is an ellipse. The code makes two calls to the DrawLine method. The first call to DrawLine is inside the container, and the second call to DrawLine is outside the container (after the call to EndContainer). The first line is clipped by the intersection of the two clipping regions. The second line is clipped only by the rectangular clipping region of the Graphics object.

Graphics graphics = e.Graphics;

GraphicsContainer graphicsContainer;

Pen redPen = new Pen(Color.Red, 2);

Pen bluePen = new Pen(Color.Blue, 2);

SolidBrush aquaBrush = new SolidBrush(Color.FromArgb(255, 180, 255, 255));

SolidBrush greenBrush = new SolidBrush(Color.FromArgb(255, 150, 250, 130));

graphics.SetClip(new Rectangle(50, 65, 150, 120));

graphics.FillRectangle(aquaBrush, 50, 65, 150, 120);

graphicsContainer = graphics.BeginContainer();

// Create a path that consists of a single ellipse.

GraphicsPath path = new GraphicsPath();

path.AddEllipse(75, 50, 100, 150);

// Construct a region based on the path.

Region region = new Region(path);

graphics.FillRegion(greenBrush, region);

graphics.SetClip(region, CombineMode.Replace);

graphics.DrawLine(redPen, 50, 0, 350, 300);

graphics.EndContainer(graphicsContainer);

graphics.DrawLine(bluePen, 70, 0, 370, 300);

The following illustration shows the two clipped lines.