Работа с клипами в PostScript | .NET

Добавить обрезку в документ PS

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

Путь обрезки в .NET можно назначить тремя способами:

На данный момент библиотека Aspose.Page для .NET предлагает первый и второй способы отсечения.

В приведенном ниже примере мы получаем круг System.Drawing.Drawing2D.GraphicsPath из прямоугольника в качестве обтравочного контура и отсекаем прямоугольник с синей заливкой в ​​том же графическом состоянии.

Чтобы добавить клип в новый PsDocument с помощью библиотеки Aspose.Page для .NET в этом примере, мы выполняем следующие шаги:

  1. Создайте выходной поток для полученного PS-файла.
  2. Создайте объект PsSaveOptions с параметрами по умолчанию.
  3. Создайте одностраничный PsDocument с уже созданным потоком вывода и сохраните параметры.
  4. Создайте новое графическое состояние.
  5. Создайте круг System.Drawing.Drawing2D.GraphicsPath из прямоугольника.
  6. Установите клип по этому пути.
  7. Установите отрисовку текущего графического состояния PsDocument.
  8. Заполните прямоугольник текущей краской.
  9. Выход из текущего состояния графики на верхний уровень.
  10. Перевести на место закрашенный прямоугольник.
  11. Обведите пунктирной линией границы того же прямоугольника над закрашенным, чтобы показать границы обрезанного залитого прямоугольника.
  12. Закройте страницу.
  13. Сохраните документ.
 1//Create an output stream for the PostScript document
 2using (Stream outPsStream = new FileStream(dataDir + "Clipping_outPS.ps", FileMode.Create))
 3{
 4    //Create save options with default values
 5    PsSaveOptions options = new PsSaveOptions();
 6
 7    // Create a new 1-paged PS Document
 8    PsDocument document = new PsDocument(outPsStream, options, false);
 9
10    //Create a graphics path from the rectangle
11    GraphicsPath rectangePath = new GraphicsPath();
12    rectangePath.AddRectangle(new RectangleF(0, 0, 300, 200));
13
14    //Save the graphics state in order to return back to this state after transformation
15    document.WriteGraphicsSave();
16
17    //Displace the current graphics state on 100 points to the right and 100 points to the bottom.
18    document.Translate(100, 100);
19
20    //Create a graphics path from the circle
21    GraphicsPath circlePath = new GraphicsPath();
22    circlePath.AddEllipse(new RectangleF(50, 0, 200, 200));
23
24    //Add a clipping by the circle to the current graphics state
25    document.Clip(circlePath);
26
27    //Set the paint in the current graphics state
28    document.SetPaint(new SolidBrush(Color.Blue));
29
30    //Fill the rectangle in the current graphics state (with the clipping)
31    document.Fill(rectangePath);
32
33    //Restore the graphics state to the previus (upper) level
34    document.WriteGraphicsRestore();
35
36    //Displace the upper level graphics state on 100 points to the right and 100 points to the bottom.
37    document.Translate(100, 100);
38
39    Pen pen = new Pen(new SolidBrush(Color.Blue), 2);
40    pen.DashStyle = DashStyle.Dash;
41
42    document.SetStroke(pen);
43
44    //Draw the rectangle in the current graphics state (has no clipping) above the clipped rectngle
45    document.Draw(rectangePath);
46
47    //Close the current page
48    document.ClosePage();
49
50    //Save the document
51    document.Save();
52}

Для Linux, MacOS и других операционных систем, отличных от Windows, мы предлагаем использовать наш пакет Nuget Aspose.Page.Drawing. Он использует серверную часть Aspose.Drawing вместо системной библиотеки System.Drawing.

Поэтому импортируйте пространство имен Aspose.Page.Drawing вместо System.Drawing. В приведенном выше фрагменте кода вместо System.Drawing.Rectangle будет использоваться Aspose.Page.Drawing.Rectangle, Aspose.Page.Drawing.Drawing2D.GraphicsPath будет использоваться вместо System.Drawing.Drawing2D.GraphicsPath и так далее. Наши примеры кода на GitHub содержат все необходимые замены.

См. работу с обрезкой в документах PS Java.


Результат запуска этого кода выглядит так:

Вырезка

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

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

  1. Создайте выходной поток для полученного PS-файла.
  2. Создайте объект PsSaveOptions с параметрами по умолчанию.
  3. Создайте одностраничный PsDocument с уже созданным потоком вывода и сохраните параметры.
  4. Создайте новое графическое состояние.
  5. Создайте шрифт.
  6. Установите клип с текстом и шрифтом.
  7. Установите отрисовку текущего графического состояния PsDocument.
  8. Заполните прямоугольник текущей краской.
  9. Выход из текущего состояния графики на верхний уровень.
  10. Перевести на место закрашенный прямоугольник.
  11. Обведите пунктирной линией границы того же прямоугольника над закрашенным, чтобы показать границы обрезанного залитого прямоугольника.
  12. Закройте страницу.
  13. Сохраните документ.
 1//Create an output stream for the PostScript document
 2using (Stream outPsStream = new FileStream(dataDir + "Clipping_outPS.ps", FileMode.Create))
 3{
 4    //Create save options with default values
 5    PsSaveOptions options = new PsSaveOptions();
 6
 7    // Create a new 1-paged PS Document
 8    PsDocument document = new PsDocument(outPsStream, options, false);
 9
10    //Create a graphics path from the rectangle
11    GraphicsPath rectangePath = new GraphicsPath();
12    rectangePath.AddRectangle(new RectangleF(0, 0, 300, 200));
13
14    //Save the graphics state in order to return back to this state after transformation
15    document.WriteGraphicsSave();
16
17    //Displace the current graphics state on 100 points to the right and 100 points to the bottom.
18    document.Translate(100, 100);
19    
20    //Set the paint in the current graphics state
21    document.SetPaint(new SolidBrush(Color.Blue));
22
23    //Create a font
24    int fontSize = 120;
25    Font font = new Font("Arial", fontSize, FontStyle.Bold);
26
27    //Clip the rectangle by text's outline
28    document.ClipText("ABC", font, 20, fontSize + 10);
29    document.Fill(rectanglePath);
30
31    //Restore the graphics state to the previus (upper) level
32    document.WriteGraphicsRestore();
33
34		//Displace the upper level graphics state on 100 points to the right and 100 points to the bottom.
35    document.Translate(100, 100);
36
37		Pen pen = new Pen(new SolidBrush(Color.Blue), 2);
38    pen.DashStyle = DashStyle.Dash;
39
40    document.SetStroke(pen);
41    
42    //Draw the rectangle in the current graphics state (has no clipping) above the clipped rectangle
43    document.Draw(rectanglePath);
44
45    //Close the current page
46    document.ClosePage();
47
48    //Save the document
49    document.Save();
50}

Для Linux, MacOS и других операционных систем, отличных от Windows, мы предлагаем использовать наш пакет Nuget Aspose.Page.Drawing. Он использует серверную часть Aspose.Drawing вместо системной библиотеки System.Drawing. Поэтому импортируйте пространство имен Aspose.Page.Drawing вместо System.Drawing. В приведенном выше фрагменте кода вместо System.Drawing.Rectangle будет использоваться Aspose.Page.Drawing.Rectangle, Aspose.Page.Drawing.Drawing2D.GraphicsPath будет использоваться вместо System.Drawing.Drawing2D.GraphicsPath и так далее. Наши примеры кода на GitHub содержат все необходимые замены.

См. работу с обрезкой в документах PS Java.


Результат запуска этого кода выглядит так:

ClippingByText

Вы можете загрузить примеры и файлы данных с сайта GitHub.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.