2012年12月3日月曜日

Extending Paint object to SVG element translation

The SVGGraphics2D is able to generate SVG elements for generic Java 2D objects, but you sometimes have your own classes such as implementations of the Java 2D Paint interface. In this case, you will need to write an ExtensionHandler that you will set on your SVGGeneratorContext .

In the following example we define the first draft of an ExtensionHandler allowing to translate a Batik implementation of the Paint interface named LinearGradientPaint.

class MyExtensionHandler extends DefaultExtensionHandler {

public SVGPaintDescriptor handlePaint(Paint paint,
SVGGeneratorContext generatorCtx) {
if (paint instanceof LinearGradientPaint) {
LinearGradientPaint gradient = (LinearGradientPaint) paint;

// Create a new SVG 'linearGradient' element to represent the
// LinearGradientPaint being used.
String id = generatorCtx.getIDGenerator().generateID("gradient");
Document doc = generatorCtx.getDOMFactory();
Element grad = doc.createElementNS
(SVGSyntax.SVG_NAMESPACE_URI,
SVGSyntax.SVG_LINEAR_GRADIENT_TAG);

// Set the relevant attributes on the 'linearGradient' element.
grad.setAttributeNS(null, SVGSyntax.SVG_ID_ATTRIBUTE, id);
grad.setAttributeNS(null, SVGSyntax.SVG_GRADIENT_UNITS_ATTRIBUTE,
SVGSyntax.SVG_USER_SPACE_ON_USE_VALUE);
Point2D pt = gradient.getStartPoint();
grad.setAttributeNS(null, "x1", pt.getX());
grad.setAttributeNS(null, "y1", pt.getY());
pt = gradient.getEndPoint();
grad.setAttributeNS(null, "x2", pt.getX());
grad.setAttributeNS(null, "y2", pt.getY());

switch (gradient.getCycleMethod()) {
case MultipleGradientPaint.REFLECT:
grad.setAttributeNS
(null, SVGSyntax.SVG_SPREAD_METHOD_ATTRIBUTE,
SVGSyntax.SVG_REFLECT_VALUE);
break;
case MultipleGradientPaint.REPEAT:
grad.setAttributeNS
(null, SVGSyntax.SVG_SPREAD_METHOD_ATTRIBUTE,
SVGSyntax.SVG_REPEAT_VALUE);
break;
// 'pad' is the default...
}

// Here we should write the transform of the gradient
// in the transform attribute...

// Here we should write the stops of the gradients as
// children elements...

return new SVGPaintDescriptor
("url(#" + ref + ")", SVGSyntax.SVG_OPAQUE_VALUE, grad);
} else {
// Let the default mechanism do its job.
return null;
}
}
}

You should then set it on the SVGGeneratorContext by using the setExtensionHandler method.
SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(myFactory);
ctx.setExtensionHandler(new MyExtensionHandler());
SVGGraphics2D g2d = new SVGGraphics2D(ctx, false);

0 件のコメント:

コメントを投稿