Робота з градієнтом у PostScript | .NET

Додайте градієнт у документ PS

У цій статті ми розглянемо способи використання градієнта в документах PS.

Градієнт - це плавний перехід одного кольору в інший. Він використовується для того, щоб зробити намальовані зображення більш реалістичними. Оскільки градієнт є різновидом фарби, очікується, що в .NET він реалізований як підклас System.Drawing.Brush. Насправді платформа .NET має дві такі пензлі:

Щоб установити фарбу або обведення в PsDocument, ми повинні передати об’єкт класу System.Drawing.Brush для малювання та об’єкт System.Drawing.Pen для обведення в відповідні методи. Бібліотека Aspose.Page для .NET обробляє всі підкласи System.Drawing.Brush, які пропонуються платформою .NET. Це System.Drawing.SolidBrush, System.Drawing.TextureBrush, System.Drawing.LinearGradientBrush, System.Drawing.PathGradientBrush і *System.Drawing.HatchBrush *. Клас System.Drawing.Pen не можна розширити, оскільки він запечатаний, але він містить System.Drawing.Brush як властивість, тому Aspose.Page для бібліотеки .NET також може використовувати повний набір пензлів також для малювання ліній і окреслення форм і тексту.

Щоб малювати графічні об’єкти градієнтом у бібліотеці Aspose.Page для .NET, необхідно створити System.Drawing.LinearGradientBrush або System.Drawing.PathGradientBrush і передати його в SetPaint () або один із методів FillText() або FillAndStrokeText(), які приймають System.Drawing.Brush як параметр.

Щоб контурувати графічні об’єкти з градієнтом у бібліотеці Aspose.Page для .NET, хтось має створити System.Drawing.LinearGradientBrush або System.Drawing.PathGradientBrush, а потім створити System.Drawing. Перо цим пензлем і, нарешті, передайте його SetStroke() або одному з методів OutlineText() або FillAndStrokeText(), який приймає *System.Drawing.Pen * як параметр.

У наведеному нижче прикладі ми демонструємо, як заповнити фігуру та текст і окреслити текст градієнтом.

Алгоритм розмальовування графічних об’єктів градієнтом у новому документі PS включає наступні кроки:

  1. Створіть вихідний потік для отриманого файлу PS.
  2. Створіть PsSaveOptions.
  3. Створіть PsDocument із уже створеним вихідним потоком і параметрами збереження.
  4. Створіть необхідний графічний шлях або шрифт в залежності від того, який об’єкт ми збираємося заповнити або окреслити.
  5. Створіть об’єкт System.Drawing.LinearGradientBrush або System.Drawing.PathGradientBrush в залежності від бажаної форми градієнта.
  6. Встановіть на цьому пензлі необхідну трансформацію.
  7. Встановіть кисть градієнта як поточну фарбу в PsDocument
  8. Заповніть графічний контур поточною фарбою або заповніть текст. Якщо ми використовуємо один із методів заповнення тексту, який приймає System.Drawing.Brush як параметр, попередній пункт можна проігнорувати.
  9. Закрийте сторінку.
  10. Збережіть документ.

Якщо нам потрібно обведення (контур) графічних об’єктів із градієнтом замість останніх 4 точок, наступним буде:

  1. Створіть об’єкт System.Drawing.Pen за допомогою пензля градієнта.
  2. Установіть це перо як поточний штрих у PsDocument.
  3. Окресліть контур графіки поточним штрихом або обведіть текст. Якщо ми використовуємо один із методів для контуру тексту, який приймає System.Drawing.Pen як параметр, попередній пункт можна проігнорувати.
  4. Закрийте сторінку.
  5. Збережіть документ.

Ми пропонуємо 5 фрагментів коду, які демонструють використання різних градієнтів.

У цьому фрагменті коду ми створюємо горизонтальний лінійний градієнт із двох кольорів, заповнюємо прямокутник, заповнюємо текст, обводимо текст цим градієнтом.

 1//Create an output stream for PostScript document
 2using (Stream outPsStream = new FileStream(dataDir + "HorizontalGradient_outPS.ps", FileMode.Create))
 3{
 4    //Create save options with A4 size
 5    PsSaveOptions options = new PsSaveOptions();
 6
 7    // Create new 1-paged PS Document
 8    PsDocument document = new PsDocument(outPsStream, options, false);
 9
10    float offsetX = 200;
11    float offsetY = 100;
12    float width = 200;
13    float height = 100;
14
15    //Create a graphics path from the first rectangle
16    GraphicsPath path = new GraphicsPath();
17    path.AddRectangle(new RectangleF(offsetX, offsetY, width, height));
18
19    //Create linear gradient brush with the rectangle as bounds, start і end colors
20    LinearGradientBrush brush = new LinearGradientBrush(new RectangleF(0, 0, width, height), Color.FromArgb(150, 0, 0, 0),
21        Color.FromArgb(50, 40, 128, 70), 0f);
22    //Create a transform for the brush. X і Y scale component must be equal to the width і the height of the rectangle respectively.
23    //Translation components are offsets of the rectangle
24    Matrix brushTransform = new Matrix(width, 0, 0, height, offsetX, offsetY);
25    //Set  the transform
26    brush.Transform = brushTransform;
27
28    //Set the paint
29    document.SetPaint(brush);
30
31    //Fill the rectangle
32    document.Fill(path);
33
34    //Fill the text with the gradient
35    Font font = new Font("Arial", 96, FontStyle.Bold);
36    document.FillAndStrokeText("ABC", font, 200, 300, brush, new Pen(new SolidBrush(Color.Black), 2));
37
38		//Set current stroke
39		document.SetStroke(brush, 5);
40    //Outline text with the gradient
41    document.OutlineText("ABC", font, 200, 400);
42
43    //Close current page
44    document.ClosePage();
45
46    //Save the document
47    document.Save();
48}

Для Linux, MacOS та інших операційних систем, відмінних від Windows, ми пропонуємо використовувати наш пакет Nuget Aspose.Page.Drawing. Він використовує бекенд Aspose.Drawing замість системної бібліотеки System.Drawing.

Тому імпортуйте простір імен Aspose.Page.Drawing замість System.Drawing. У наведених вище та наступних фрагментах коду Aspose.Page.Drawing.RectangleF використовуватиметься замість System.Drawing.RectangleF, Aspose.Page.Drawing.Drawing2D.GraphicsPath використовуватиметься замість System.Drawing.Drawing2D.GraphicsPath тощо. Наші приклади коду на GitHub містять усі необхідні заміни.

Результат виконання цього коду виглядає як

Додати горизонтальний градієнт

У цьому фрагменті коду ми створюємо вертикальний лінійний градієнт із 5 кольорів і заповнюємо цим градієнтом прямокутник.

 1//Create an output stream for PostScript document
 2using (Stream outPsStream = new FileStream(dataDir + "VerticalGradient_outPS.ps", FileMode.Create))
 3{
 4    //Create save options with A4 size
 5    PsSaveOptions options = new PsSaveOptions();
 6
 7    // Create new 1-paged PS Document
 8    PsDocument document = new PsDocument(outPsStream, options, false);
 9
10    float offsetX = 200;
11    float offsetY = 100;
12    float width = 200;
13    float height = 100;
14
15    //Create graphics path from the first rectangle
16    GraphicsPath path = new GraphicsPath();
17    path.AddRectangle(new RectangleF(offsetX, offsetY, width, height));
18
19    //Create an array of interpolation colors
20    Color[] colors = { Color.Red, Color.Green, Color.Blue, Color.Orange, Color.DarkOliveGreen };
21    float[] positions = { 0.0f, 0.1873f, 0.492f, 0.734f, 1.0f };
22    ColorBlend colorBlend = new ColorBlend();
23    colorBlend.Colors = colors;
24    colorBlend.Positions = positions;
25
26    //Create linear gradient brush with the rectangle as bounds, start і end colors
27    LinearGradientBrush brush = new LinearGradientBrush(new RectangleF(0, 0, width, height), Color.Beige, Color.DodgerBlue, 0f);
28    //Set interpolation colors
29    brush.InterpolationColors = colorBlend;
30    //Create a transform for the brush. X і Y scale component must be equal to width і height of the rectangle correspondingly.
31    //Translation components are offsets of the rectangle
32    Matrix brushTransform = new Matrix(width, 0, 0, height, offsetX, offsetY);
33    //Rotate the graphics state to get colors change in vertical direction from up to down
34    brushTransform.Rotate(90);
35    //Set the transform
36    brush.Transform = brushTransform;
37
38    //Set the paint
39    document.SetPaint(brush);
40
41    //Fill the rectangle
42    document.Fill(path);
43
44    //Close current page
45    document.ClosePage();
46
47    //Save the document
48    document.Save();
49}

Ось і результат

Додати вертикальний градієнт

У цьому фрагменті коду ми створюємо діагональний лінійний градієнт із 2 кольорів і заповнюємо цим градієнтом прямокутник.

 1//Create an output stream for PostScript document
 2using (Stream outPsStream = new FileStream(dataDir + "DiagonaGradient_outPS.ps", FileMode.Create))
 3{
 4    //Create save options with A4 size
 5    PsSaveOptions options = new PsSaveOptions();
 6
 7    // Create new 1-paged PS Document
 8    PsDocument document = new PsDocument(outPsStream, options, false);
 9
10    float offsetX = 200;
11    float offsetY = 100;
12    float width = 200;
13    float height = 100;
14
15    //Create a graphics path from the first rectangle
16    GraphicsPath path = new GraphicsPath();
17    path.AddRectangle(new RectangleF(offsetX, offsetY, width, height));
18
19    //Create linear gradient brush with the rectangle as bounds, start і end colors
20    LinearGradientBrush brush = new LinearGradientBrush(new RectangleF(0, 0, width, height), Color.FromArgb(255, 255, 0, 0),
21        Color.FromArgb(255, 0, 0, 255), 0f);
22
23    //Create a transform for brush. X і Y scale component must be equal to width і height of the rectangle correspondingly.
24    //Translation components are offsets of the rectangle        
25    Matrix brushTransform = new Matrix(width, 0, 0, height, offsetX, offsetY);
26    //Rotate the gradient, than scale і translate to get visible a color transition in required rectangle
27    brushTransform.Rotate(-45);
28    float hypotenuse = (float)System.Math.Sqrt(200 * 200 + 100 * 100);
29    float ratio = hypotenuse / 200;
30    brushTransform.Scale(-ratio, 1);
31    brushTransform.Translate(100 / brushTransform.Elements[0], 0);
32
33    //Set the transform
34    brush.Transform = brushTransform;
35
36    //Set the paint
37    document.SetPaint(brush);
38
39    //Fill the rectangle
40    document.Fill(path);
41
42    //Close current page
43    document.ClosePage();
44
45    //Save the document
46    document.Save();
47}

Ось і результат

Додати діагональний градієнт

У цьому фрагменті коду ми створюємо радіальний градієнт із 2 кольорів і заповнюємо цим градієнтом коло.

 1//Create an output stream for PostScript document
 2using (Stream outPsStream = new FileStream(dataDir + "RadialGradient1_outPS.ps", FileMode.Create))
 3{
 4    //Create save options with A4 size
 5    PsSaveOptions options = new PsSaveOptions();
 6
 7    // Create new 1-paged PS Document
 8    PsDocument document = new PsDocument(outPsStream, options, false);
 9
10    float offsetX = 200;
11    float offsetY = 100;
12    float width = 200;
13    float height = 200;
14
15    //Create a graphics path from the rectangle bounds
16    RectangleF bounds = new RectangleF(offsetX, offsetY, width, height);
17    GraphicsPath path = new GraphicsPath();
18    path.AddEllipse(bounds);
19
20    //Create і fill color blend object
21    Color[] colors = { Color.White, Color.White, Color.Blue };
22    float[] positions = { 0.0f, 0.2f, 1.0f };
23    ColorBlend colorBlend = new ColorBlend();
24    colorBlend.Colors = colors;
25    colorBlend.Positions = positions;
26
27    GraphicsPath brushRect = new GraphicsPath();
28    brushRect.AddRectangle(new RectangleF(0, 0, width, height));
29
30    //Create path gradient brush with the rectangle as bounds
31    PathGradientBrush brush = new PathGradientBrush(brushRect);
32    //Set interpolation colors
33    brush.InterpolationColors = colorBlend;
34    //Create a transform for the brush. X і Y scale component must be equal to width і height of the rectangle correspondingly.
35    //Translation components are offsets of the rectangle
36    Matrix brushTransform = new Matrix(width, 0, 0, height, offsetX, offsetY);
37    //Set the transform
38    brush.Transform = brushTransform;
39
40    //Set the paint
41    document.SetPaint(brush);
42
43    //Fill the rectangle
44    document.Fill(path);
45
46    //Close current page
47    document.ClosePage();
48
49    //Save the document
50    document.Save();
51}

Результат

Додати зображення радіального градієнта1

У цьому фрагменті коду ми створюємо радіальний градієнт із 6 кольорів і заливаємо цим градієнтом прямокутник.

 1//Create an output stream for PostScript document
 2using (Stream outPsStream = new FileStream(dataDir + "RadialGradient2_outPS.ps", FileMode.Create))
 3{
 4    //Create save options with A4 size
 5    PsSaveOptions options = new PsSaveOptions();
 6
 7    // Create new 1-paged PS Document
 8    PsDocument document = new PsDocument(outPsStream, options, false);
 9
10    float offsetX = 200;
11    float offsetY = 100;
12    float width = 200;
13    float height = 200;
14
15    //Create a graphics path from the rectangle bounds
16    RectangleF bounds = new RectangleF(offsetX, offsetY, width, height);
17    GraphicsPath path = new GraphicsPath();
18    path.AddRectangle(bounds);
19
20    //Create і fill color blend object
21    Color[] colors = { Color.Green, Color.Blue, Color.Black, Color.Yellow, Color.Beige, Color.Red };
22    float[] positions = { 0.0f, 0.2f, 0.3f, 0.4f, 0.9f, 1.0f };
23    ColorBlend colorBlend = new ColorBlend();
24    colorBlend.Colors = colors;
25    colorBlend.Positions = positions;
26
27    GraphicsPath brushRect = new GraphicsPath();
28    brushRect.AddRectangle(new RectangleF(0, 0, width, height));
29
30    //Create path gradient brush with the rectangle as bounds
31    PathGradientBrush brush = new PathGradientBrush(brushRect);
32    //Set interpolation colors
33    brush.InterpolationColors = colorBlend;
34    //Create a transform for the brush. X і Y scale component must be equal to width і height of the rectangle correspondingly.
35    //Translation components are offsets of the rectangle
36    Matrix brushTransform = new Matrix(width, 0, 0, height, offsetX, offsetY);
37    //Set the transform
38    brush.Transform = brushTransform;
39
40    //Set the paint
41    document.SetPaint(brush);
42
43    //Fill the rectangle
44    document.Fill(path);
45
46    //Close current page
47    document.ClosePage();
48
49    //Save the document
50    document.Save();
51}

Результат

Додати зображення радіального градієнта2

Див. роботу з градієнтом у документах PS in Java.

Ви можете завантажити приклади і файли даних з GitHub.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.