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

Спрямление участков кривой

В объекте GraphicsPath хранятся последовательности линий и сплайнов Безье. К контуру можно добавлять различные типы кривых (эллипсы, дуги и фундаментальные сплайны), но перед сохранением в контуре каждая кривая преобразуется в сплайн Безье. Спрямление контура заключается в преобразовании всех сплайнов Безье в последовательность отрезков прямых линий. На приведенном ниже рисунке изображен контур до и после спрямления.

Спрямление контура

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

Использование преобразований в управляемом GDI+

Аффинные преобразования — это поворот, масштабирование, отражение, наклон и сдвиг. В интерфейсе GDI+ класс Matrix предоставляет основные средства для осуществления аффинных преобразований над векторными рисунками, изображениями и текстом.

Использование объемного преобразования

Объемное преобразование является свойством класса Graphics. Числа, определяющие объемное преобразование, хранятся в объекте Matrix, представляющем собой матрицу размером 3×3. Классы Matrix и Graphics содержат различные методы для установки элементов матрицы объемного преобразования.

Different Types of Transformations

In the following example, the code first creates a 50×50 rectangle and locates it at the origin (0, 0). The origin is at the upper-left corner of the client area.

Rectangle rect = new Rectangle(0, 0, 50, 50);

Pen pen = new Pen(Color.FromArgb(128, 200, 0, 200), 2);

e.Graphics.DrawRectangle(pen, rect);

The following code applies a scaling transformation that expands the rectangle by a factor of 1.75 in the x direction and shrinks the rectangle by a factor of 0.5 in the y direction:

e.Graphics.ScaleTransform(1.75f, 0.5f);

e.Graphics.DrawRectangle(pen, rect);

The result is a rectangle that is longer in the x direction and shorter in the y direction than the original.

To rotate the rectangle instead of scaling it, use the following code:

e.Graphics.ResetTransform();

e.Graphics.RotateTransform(28); // 28 degrees

e.Graphics.DrawRectangle(pen, rect);

To translate the rectangle, use the following code:

e.Graphics.ResetTransform();

e.Graphics.TranslateTransform(150, 150);

e.Graphics.DrawRectangle(pen, rect);

Различные типы преобразований

В следующем примере код создает прямоугольник 50×50 и помещает его в точку начала координат (0, 0). Начало координат располагается в верхнем левом углу клиентской области.

---------

В следующем коде к прямоугольнику применяется масштабирование; коэффициент для оси x равен 1,75, а для оси y — 0,5.

--

Результатом преобразования является прямоугольник, который длиннее исходного по оси x и короче его по оси y.

Чтобы вместо масштабирования прямоугольника осуществить его поворот, используйте следующий код:

---

Чтобы преобразовать прямоугольник, можно использовать следующий код:

---------

Why Transformation Order Is Significant

A single Matrix object can store a single transformation or a sequence of transformations. The latter is called a composite transformation. The matrix of a composite transformation is obtained by multiplying the matrices of individual transformations.

Composite Transform Examples

In a composite transformation, the order of individual transformations is important. For example, if you first rotate, then scale, then translate, you get a different result than if you first translate, then rotate, then scale. In GDI+, composite transformations are built from left to right. If S, R, and T are scale, rotation, and translation matrices respectively, then the product SRT (in that order) is the matrix of the composite transformation that first scales, then rotates, then translates. The matrix produced by the product SRT is different from the matrix produced by the product TRS.

One reason order is significant is that transformations like rotation and scaling are done with respect to the origin of the coordinate system. Scaling an object that is centered at the origin produces a different result than scaling an object that has been moved away from the origin. Similarly, rotating an object that is centered at the origin produces a different result than rotating an object that has been moved away from the origin.

The following example combines scaling, rotation and translation (in that order) to form a composite transformation. The argument Append passed to the RotateTransform method indicates that the rotation will follow the scaling. Likewise, the argument Append passed to the TranslateTransform method indicates that the translation will follow the rotation. Append and Prepend are members of the MatrixOrder enumeration.

Rectangle rect = new Rectangle(0, 0, 50, 50);

Pen pen = new Pen(Color.FromArgb(128, 200, 0, 200), 2);

e.Graphics.ResetTransform();

e.Graphics.ScaleTransform(1.75f, 0.5f);

e.Graphics.RotateTransform(28, MatrixOrder.Append);

e.Graphics.TranslateTransform(150, 150, MatrixOrder.Append);

e.Graphics.DrawRectangle(pen, rect);