How to add a shading pattern to a custom shape

2019-03-04 06:07发布

问题:

I have drawn an equilateral triangle as follows using iText

canvas.setColorStroke(BaseColor.BLACK);
int x = start.getX();
int y = start.getY();
canvas.moveTo(x,y);        
canvas.lineTo(x + side,y);
canvas.lineTo(x + (side/2), (float)(y+(side*Math.sin(convertToRadian(60)))));
canvas.closePathStroke();

I wish to multi color gradient in this shape i.e. fill it with shading comprising of BaseColor.PINK and BaseColor.BLUE. I just can't find a way to do this with iText ?

回答1:

I've created an example called ShadedFill that fills the triangle you are drawing using a shading pattern that goes from pink to blue as show in the shaded_fill.pdf:

PdfContentByte canvas = writer.getDirectContent();
float x = 36;
float y = 740;
float side = 70;
PdfShading axial = PdfShading.simpleAxial(writer, x, y,
        x + side, y, BaseColor.PINK, BaseColor.BLUE);
PdfShadingPattern shading = new PdfShadingPattern(axial);
canvas.setShadingFill(shading);
canvas.moveTo(x,y);        
canvas.lineTo(x + side, y);
canvas.lineTo(x + (side / 2), (float)(y + (side * Math.sin(Math.PI / 3))));
canvas.closePathFillStroke();

As you can see, you need to create a PdfShading object. I created an axial shading that varies from pink to blue from the coordinate (x, y) to the coordinate (x + side, y). With this axial shading, you can create a PdfShadingPattern that can be used as a parameter of the setShadingFill() method to set the fill color for the canvas.

See ShadedFill for the full source code.



标签: itext