Trabalhar com Gradiente em ficheiro PS | Java
Adicionar Gradiente em Documento PS
Neste artigo, consideramos as formas como um gradiente pode ser utilizado em documentos de PS.
O gradiente é uma transição suave de uma cor para outra. É utilizado para tornar as imagens desenhadas mais realistas. Como o gradiente é um tipo de tinta, é esperado que em Java seja implementado como uma subclasse de java.awt.Paint. Na verdade, a plataforma Java possui duas destas tintas:
- java.awt.LinearGradientPaint
- java.awt.RadialGradientPaint
Existe também java.awt.GradientPaint, mas é apenas um caso particular de java.awt.LinearGradientPaint.
Para definir uma pintura ou um traço em PsDocument, precisamos de passar um objeto da classe java.awt.Paint para uma pintura e um objeto da classe java.awt.Stroke para o traço nos respetivos métodos. A biblioteca Aspose.Page para Java processa todas as classes importantes implementadas em java.awt.Paint oferecidas pela plataforma Java. São elas: java.awt.Color, java.awt.TexturePaint, java.awt.LinearGradientPaint e java.awt.RadialGradientPaint. A cor do traço em Java é atribuída separadamente das propriedades do traço no objeto java.awt.Stroke, utilizando novamente java.awt.Paint. Por conseguinte, a biblioteca Aspose.Page para Java também pode utilizar um conjunto completo de implementações de pintura para desenhar linhas e delinear formas e texto.
Para pintar objetos gráficos com um gradiente na biblioteca Aspose.Page para Java, é necessário criar java.awt.LinearGradientPaint ou java.awt.RadialGradientPaint e passá-los para setPaint() ou um dos métodos fillText() ou fillAndStrokeText() que aceitam java.awt.Paint como parâmetro.
Para contornar os objetos gráficos com um gradiente na biblioteca Aspose.Page para Java, é necessário passar java.awt.LinearGradientPaint ou java.awt.RadialGradientPaint também para setPaint() ou um dos métodos outlineText() ou fillAndStrokeText() que aceitam pintura de traços como parâmetro.
No exemplo abaixo, demonstramos como preencher uma forma e um texto e contornar o texto com um gradiente.
Um algoritmo para pintar objetos gráficos com um gradiente num novo documento PS inclui os seguintes passos:
- Crie um fluxo de saída para o ficheiro PS resultante.
- Crie PsSaveOptions.
- Crie PsDocument com o fluxo de saída já criado e as opções de guardar.
- Crie o caminho gráfico ou a fonte necessária, dependendo do objeto que iremos preencher ou contornar.
- Crie um objeto a partir de java.awt.LinearGradientPaint ou java.awt.RadialGradientPaint, dependendo da forma desejada do gradiente.
- Defina a transformação necessária neste pincel.
- Defina o pincel de gradiente como a pintura atual no PsDocument
- Preencha o percurso gráfico com a pintura atual ou preencha um texto. Se utilizarmos um dos métodos de preenchimento de texto que aceita java.awt.Paint como parâmetro, o ponto anterior pode ser ignorado.
- Feche a página.
- Guarde o documento.
Se precisarmos de traçar (contornar) objetos gráficos com um gradiente em vez dos últimos 4 pontos, o seguinte será:
- Defina o gradiente como a pintura atual no PsDocument.
- Crie o objeto java.awt.Stroke.
- Defina este traço como o traço atual no PsDocument.
- Contorne o percurso gráfico com o traço atual ou contorne o texto. Se utilizarmos um dos métodos de contorno de texto que aceita java.awt.Stroke como parâmetro, o ponto anterior pode ser ignorado.
- Feche a página.
- Guarde o documento.
Oferecemos 5 excertos de código separados que demonstram a utilização de diferentes gradientes.
Neste excerto de código, criamos um gradiente linear horizontal a partir de duas cores, preenchemos um retângulo, preenchemos um texto e contornamos um texto com este gradiente.
1// Paint rectangle and text and draw text with horizontal gradient fill in PS document.
2
3String outputFileName = "HorizontalGradient_outPS.ps";
4
5//Create save options with A4 size
6PsSaveOptions options = new PsSaveOptions();
7
8// Create new 1-paged PS Document
9PsDocument document = new PsDocument(getOutputDir() + outputFileName, options, false);
10
11float offsetX = 200;
12float offsetY = 100;
13float width = 200;
14float height = 100;
15
16//Create graphics path from the first rectangle
17java.awt.geom.GeneralPath path = new java.awt.geom.GeneralPath();
18path.append(new Rectangle2D.Float(offsetX, offsetY, width, height), false);
19
20//Create linear gradient brush with rectangle as a bounds, start and end colors and transformation matrix
21LinearGradientPaint paint = new LinearGradientPaint(new Point2D.Float(0, 0), new Point2D.Float(200, 100),
22 new float [] {0, 1}, new Color [] {new Color(0, 0, 0, 150), new Color(40, 128, 70, 50)},
23 MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB,
24 new AffineTransform(width, 0, 0, height, offsetX, offsetY));
25
26//Set paint
27document.setPaint(paint);
28
29//Fill the rectangle
30document.fill(path);
31
32//Fill text with gradient
33java.awt.Font font = new java.awt.Font("Arial", java.awt.Font.BOLD, 96);
34document.fillAndStrokeText("ABC", font, 200, 300, paint, Color.BLACK, new java.awt.BasicStroke(2));
35
36//Set current stroke
37document.setStroke(new java.awt.BasicStroke(5));
38//Outline text with gradient
39document.outlineText("ABC", font, 200, 400);
40
41//Close current page
42document.closePage();
43
44//Save the document
45document.save();O resultado da execução deste código é apresentado como

Neste excerto de código, criamos um gradiente linear vertical com 5 cores e preenchemos um retângulo com esse gradiente.
1// Paint rectangle with vertical gradient fill in PS document.
2
3String outputFileName = "VerticalGradient_outPS.ps";
4
5//Create save options with A4 size
6PsSaveOptions options = new PsSaveOptions();
7
8// Create new 1-paged PS Document
9PsDocument document = new PsDocument(getOutputDir() + outputFileName, options, false);
10
11float offsetX = 200;
12float offsetY = 100;
13float width = 200;
14float height = 100;
15
16//Create graphics path from the first rectangle
17java.awt.geom.GeneralPath path = new java.awt.geom.GeneralPath();
18path.append(new Rectangle2D.Float(offsetX, offsetY, width, height), false);
19
20//Create an array of interpolation colors
21Color[] colors = { Color.RED, Color.GREEN, Color.BLUE, Color.ORANGE, new Color(107, 142, 35) }; // DarkOliveGreen
22float[] positions = { 0.0f, 0.1873f, 0.492f, 0.734f, 1.0f };
23
24//Create the gradient transform. Scale components in the transform must be equal to width and heigh of the rectangle.
25//Translation components are offsets of the rectangle.
26AffineTransform transform = new AffineTransform(width, 0, 0, height, offsetX, offsetY);
27//Rotate the gradient on 90 degrees around an origin
28transform.rotate(Math.toRadians(90));
29
30//Create vertical linear gradient paint.
31LinearGradientPaint paint = new LinearGradientPaint(new Point2D.Float(0, 0), new Point2D.Float(200, 100),
32 positions, colors, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB,
33 transform);
34
35//Set paint
36document.setPaint(paint);
37
38//Fill the rectangle
39document.fill(path);
40
41//Close current page
42document.closePage();
43
44//Save the document
45document.save();
Neste trecho de código, criamos um gradiente linear diagonal a partir de 2 cores e preenchemos um retângulo com esse gradiente.
1// Paint rectangle with diagonal gradient fill in PS document.
2
3String outputFileName = "DiagonalGradient_outPS.ps";
4
5//Create save options with A4 size
6PsSaveOptions options = new PsSaveOptions();
7
8// Create new 1-paged PS Document
9PsDocument document = new PsDocument(getOutputDir() + outputFileName, options, false);
10
11float offsetX = 200;
12float offsetY = 100;
13float width = 200;
14float height = 100;
15
16//Create graphics path from the first rectangle
17java.awt.geom.GeneralPath path = new java.awt.geom.GeneralPath();
18path.append(new Rectangle2D.Float(offsetX, offsetY, width, height), false);
19
20//Create the gradient transform. Scale components in the transform must be equal to width and heigh of the rectangle.
21//Translation components are offsets of the rectangle.
22AffineTransform transform = new AffineTransform(200, 0, 0, 100, 200, 100);
23//Rotate gradient, than scale and translate to get visible color transition in required rectangle
24transform.rotate(-45 * (Math.PI / 180));
25float hypotenuse = (float) Math.sqrt(200 * 200 + 100 * 100);
26float ratio = hypotenuse / 200;
27transform.scale(-ratio, 1);
28transform.translate(100 / transform.getScaleX(), 0);
29
30//Create diagonal linear gradient paint.
31LinearGradientPaint paint = new LinearGradientPaint(new Point2D.Float(0, 0), new Point2D.Float(200, 100),
32 new float [] {0, 1}, new Color [] {Color.RED, Color.BLUE}, MultipleGradientPaint.CycleMethod.NO_CYCLE,
33 MultipleGradientPaint.ColorSpaceType.SRGB, transform);
34
35//Set paint
36document.setPaint(paint);
37
38//Fill the rectangle
39document.fill(path);
40
41//Close current page
42document.closePage();
43
44//Save the document
45document.save();
Neste trecho de código, criamos um gradiente radial a partir de 2 cores e preenchemos um círculo com esse gradiente.
1// Paint rectangle with radial gradient fill in PS document.
2
3String outputFileName = "RadialGradient1_outPS.ps";
4
5//Create save options with A4 size
6PsSaveOptions options = new PsSaveOptions();
7
8// Create new 1-paged PS Document
9PsDocument document = new PsDocument(getOutputDir() + outputFileName, options, false);
10
11float offsetX = 200;
12float offsetY = 100;
13float width = 200;
14float height = 100;
15
16//Create a circle
17Ellipse2D.Float circle = new Ellipse2D.Float(offsetX, offsetY, width, height);
18
19//Create arrays of colors and fractions for the gradient.
20Color[] colors = { Color.WHITE, Color.WHITE, Color.BLUE };
21float[] fractions = { 0.0f, 0.2f, 1.0f };
22
23//Create horizontal linear gradient paint. Scale components in the transform must be equal to width and heigh of the rectangle.
24//Translation components are offsets of the rectangle.
25AffineTransform transform = new AffineTransform(width, 0, 0, height, offsetX, offsetY);
26
27//Create radial linear gradient paint.
28RadialGradientPaint paint = new RadialGradientPaint(new Point2D.Float(64, 64), 68, new Point2D.Float(24, 24),
29 fractions, colors, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB,
30 transform);
31
32//Set paint
33document.setPaint(paint);
34
35//Fill the rectangle
36document.fill(circle);
37
38//Close current page
39document.closePage();
40
41//Save the document
42document.save();O resultado

Neste trecho de código, criamos um gradiente radial a partir de 6 cores e preenchemos um retângulo com esse gradiente.
1// Paint rectangle with radial gradient fill in PS document.
2
3String outputFileName = "RadialGradient2_outPS.ps";
4
5//Create save options with A4 size
6PsSaveOptions options = new PsSaveOptions();
7
8// Create new 1-paged PS Document
9PsDocument document = new PsDocument(getOutputDir() + outputFileName, options, false);
10
11float offsetX = 200;
12float offsetY = 100;
13float width = 200;
14float height = 100;
15
16//Create a rectangle
17Rectangle2D.Float rectangle = new Rectangle2D.Float(offsetX, offsetY, width, height);
18
19//Create arrays of colors and fractions for the gradient.
20Color[] colors = { Color.GREEN, Color.BLUE, Color.BLACK, Color.YELLOW, new Color(245, 245, 220), Color.RED };
21float[] fractions = { 0.0f, 0.2f, 0.3f, 0.4f, 0.9f, 1.0f };
22
23//Create horizontal linear gradient paint. Scale components in the transform must be equal to width and heigh of the rectangle.
24//Translation components are offsets of the rectangle.
25AffineTransform transform = new AffineTransform(width, 0, 0, height, offsetX, offsetY);
26
27//Create radial gradient paint.
28RadialGradientPaint paint = new RadialGradientPaint(new Point2D.Float(300, 200), 100, new Point2D.Float(300, 200),
29 fractions, colors, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB,
30 transform);
31
32//Set paint
33document.setPaint(paint);
34
35//Fill the rectangle
36document.fill(rectangle);
37
38//Close current page
39document.closePage();
40
41//Save the document
42document.save();O resultado

Veja como trabalhar com gradiente em documentos PS em .NET.
Pode descarregar exemplos e ficheiros de dados do GitHub.