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

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

У объекта Graphics имеются методы для отображения векторной и растровой графики, а также текста, например методы DrawLine, DrawImage и DrawString. Объект Graphics содержит также некоторые свойства, влияющие на качество и ориентацию отображаемых объектов. Например, свойство "режим сглаживания" определяет, следует ли применять сглаживание к прямым и кривым линиям, а свойство "объемное преобразование" влияет на расположение и поворот рисуемых объектов.

Объект Graphics привязывается к конкретному устройству отображения. При использовании объекта Graphics для рисования в окне этот объект Graphics также привязывается к рассматриваемому окну.

Объект Graphics можно рассматривать как контейнер, потому что он хранит набор свойств, влияющих на отображение, и привязывается к конкретному устройству. Можно создать вторичный контейнер внутри существующего объекта Graphics, используя вызов метода BeginContainer объекта Graphics.

Управление состоянием объекта Graphics

Класс Graphics является ключевым элементом интерфейса GDI+. Чтобы нарисовать что-либо, необходимо получить объект Graphics, задать его свойства и вызвать его методы (DrawLine, DrawImage, DrawString и т. д.).

В данном примере вызывается метод DrawRectangle класса Graphics. Первым параметром, передаваемым методу DrawRectangle, является объект Pen.

----

Состояние объекта Graphics

Объект Graphics предоставляет более широкие функции, чем функции рисования, такие как DrawLine или DrawRectangle. Объект Graphics также осуществляет поддержку графического состояния, которое можно подразделить на следующие категории:

  • Параметры качества

  • Преобразования

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

Quality Settings

A Graphics object has several properties that influence the quality of the items that are drawn. For example, you can set the TextRenderingHint property to specify the type of antialiasing (if any) applied to text. Other properties that influence quality are SmoothingMode, CompositingMode, CompositingQuality, and InterpolationMode.

The following example draws two ellipses, one with the smoothing mode set to AntiAlias and one with the smoothing mode set to HighSpeed:

Graphics graphics = e.Graphics;

Pen pen = new Pen(Color.Blue);

graphics.SmoothingMode = SmoothingMode.AntiAlias;

graphics.DrawEllipse(pen, 0, 0, 200, 100);

graphics.SmoothingMode = SmoothingMode.HighSpeed;

graphics.DrawEllipse(pen, 0, 150, 200, 100);

Transformations

A Graphics object maintains two transformations (world and page) that are applied to all items drawn by that Graphics object. Any affine transformation can be stored in the world transformation. Affine transformations include scaling, rotating, reflecting, skewing, and translating. The page transformation can be used for scaling and for changing units (for example, pixels to inches). For more information, see Coordinate Systems and Transformations.

The following example sets the world and page transformations of a Graphics object. The world transformation is set to a 30-degree rotation. The page transformation is set so that the coordinates passed to the second DrawEllipse will be treated as millimeters instead of pixels. The code makes two identical calls to the DrawEllipse method. The world transformation is applied to the first DrawEllipse call, and both transformations (world and page) are applied to the second DrawEllipse call.

Graphics graphics = e.Graphics;

Pen pen = new Pen(Color.Red);

graphics.ResetTransform();

graphics.RotateTransform(30); // world transformation

graphics.DrawEllipse(pen, 0, 0, 100, 50);

graphics.PageUnit = GraphicsUnit.Millimeter; // page transformation

graphics.DrawEllipse(pen, 0, 0, 100, 50);