Your needs in matter of styling may be different from the two provided options (XML presentation attributes or CSS inline stylesheets).
For example, you may want to put the CSS properties in a SVG style element section and reference them through the class attribute.
In this case you will need to define a new StyleHandler as below.
public class StyleSheetStyleHandler implements StyleHandler {
// The CDATA section that holds the CSS stylesheet.
private CDATASection styleSheet;
// Build the handler with a reference to the stylesheet section.
public StyleSheetStyleHandler(CDATASection styleSheet) {
this.styleSheet = styleSheet;
}
public void setStyle(Element element, Map styleMap,
SVGGeneratorContext generatorContext) {
Iterator iter = styleMap.keySet().iterator();
// Create a new class in the style sheet.
String id = generatorContext.getIDGenerator().generateID("C");
styleSheet.appendData("."+ id +" {");
// Append each key/value pair.
while (iter.hasNext()) {
String key = (String) iter.next();
String value = (String) styleMap.get(key);
styleSheet.appendData(key + ":" + value + ";");
}
styleSheet.appendData("}\n");
// Reference the stylesheet class on the element to be styled.
element.setAttributeNS(null, "class", id);
}
}
Then you can create and use an SVGGraphics2D with a correctly configured SVGGeneratorContext .
// Configure the SVGGraphics2D for a given Document myFactory.
SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(myFactory);
CDATASection styleSheet = myFactory.createCDATASection("");
ctx.setStyleHandler(new StyleSheetStyleHandler(styleSheet));
SVGGraphics2D g2d = new SVGGraphics2D(ctx, false);
// Use the g2d to draw (e.g., component.paint(g2d)).
// Add a stylesheet to the definition section.
SVGSVGElement root = (SVGSVGElement) g2d.getRoot();
Element defs = root.getElementById(SVGSyntax.ID_PREFIX_GENERIC_DEFS);
Element style = myFactory.createElementNS (SVGSyntax.SVG_NAMESPACE_URI, SVGSyntax.SVG_STYLE_TAG);
style.setAttributeNS(null, SVGSyntax.SVG_TYPE_ATTRIBUTE, "text/css");
style.appendChild(styleSheet);
defs.appendChild(style);
// Dump the root content to a given Writer
myWriter. g2d.stream(root, myWriter);
0 件のコメント:
コメントを投稿