Graphics2D implementation that creates SVG output. After rendering the graphics via the SVGGraphics2D, you can retrieve an SVG element (see getSVGElement()) or an SVG document (see getSVGDocument()) containing your content. UsageUsing the SVGGraphics2D class is straightforward. First, create an instance specifying the height and width of the SVG element that will be created. Then, use standard Java2D API calls to draw content into the element. Finally, retrieve the SVG element that has been accumulated. For example:
SVGGraphics2D g2 = new SVGGraphics2D(300, 200);
g2.setPaint(Color.RED);
g2.draw(new Rectangle(10, 10, 280, 180));
String svgElement = g2.getSVGElement();For the content generation step, you can make use of third party libraries, such as JFreeChart, that render output using standard Java2D API calls. Rendering Hints
The SVGGraphics2D supports a couple of custom rendering hints - for details, refer to the SVGHints class documentation. Other Notes
Some additional notes:
- Images are supported, but for methods with an
ImageObserverparameter note that the observer is ignored completely. In any case, using images that are not fully loaded already would not be a good idea in the context of generating SVG data/files; - the
getFontMetrics(java.awt.Font)andgetFontRenderContext()methods return values that come from an internalBufferedImage, this is a short-cut and we don't know if there are any negative consequences (if you know of any, please let us know and we'll add the info here or find a way to fix it); - there are settings to control the number of decimal places used to write the coordinates for geometrical elements (default 2dp) and transform matrices (default 6dp). These defaults may change in a future release.
- when an HTML page contains multiple SVG elements, the items within the DEFS element for each SVG element must have IDs that are unique across all SVG elements in the page. We auto-populate the
defsKeyPrefixattribute to help ensure that unique IDs are generated.
For some demos showing how to use this class, look at the JFree-Demos project at GitHub: https://github.com/jfree/jfree-demos.
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static enumIdentifies the I2P console theme for SVG post-processing.Field Summary
FieldsModifier and TypeFieldDescriptionprivate Arc2DAn instance that is lazily instantiated in draw/fillArc and then subsequently reused to avoid creating a lot of garbage.private ColorThe background color, used by clearRect().private booleanA flag that controls whether or not the KEY_STROKE_CONTROL hint is checked.private ShapeThe user clip (can be null).private static final StringThe prefix for keys used to identify clip paths.A list of the registered clip regions.private StringThe reference for the current clip.private ColorThe color used for drawing text.private CompositeThe alpha composite applied to the draws.private static final StringSVG name of the default stroke cap.private static final StringSVG name of the default stroke join.private StringA prefix for the keys used in the DEFS element.private GraphicsConfigurationThe device configuration (this is lazily instantiated in the getDeviceConfiguration() method).A set of element IDs.private StringThe filename prefix for images that are referenced rather than embedded but don't have anhrefsupplied via theSVGHints.KEY_IMAGE_HREFhint.private StringThe filename suffix for images that are referenced rather than embedded but don't have anhrefsupplied via theSVGHints.KEY_IMAGE_HREFhint.private StringCached getSVGFillStyle() result, invalidated on setPaint/setComposite.private booleanTrue while the cached fill style is current.private BufferedImageA hidden image used for font metrics.private Graphics2DGraphics of the cached font metric image.private FontThe last font that was set.private static final PatternRegex pattern for extractingfont-familyandfont-sizefrom inlinestyleattributes and converting them to shorthand CSS classes.private FontMapperMaps font family names to alternates (or leaves them unchanged).private final FontRenderContextThe font render context.private SVGUnitsThe font size units.private intThe number of decimal places to use when writing coordinates for geometrical shapes.private booleanWhen true, the next draw(Path2D) emits a glow-filtered path before the original.private StringIf the current paint is an instance ofGradientPaint, this field will contain the reference id that is used in the DEFS element for that linear gradient.private Map<GradientPaintKey, String> A map of all the gradients used, and the corresponding id.private final intThe height of the drawing area.private final RenderingHintsRendering hints (see SVGHints).private List<ImageElement> A list of images that are referenced but not embedded in the SVG.private Line2DAn instance that is lazily instantiated in drawLine and then subsequently reused to avoid creating a lot of garbage.private static final PatternExtracts the CSS class name from aclass="..."attribute within a line run.private static final PatternMatches one self-closing<line>element, used to walk a run element by element.private static final StringMatches a single self-closing<line>element with its trailing whitespace.private static final PatternMatches consecutive runs of self-closing<line>elements.private Map<LinearGradientPaintKey, String> A map of all the linear gradients used, and the corresponding id.private Ellipse2DAn instance that is lazily instantiated in draw/fillOval and then subsequently reused to avoid creating a lot of garbage.private PaintThe paint used for filling.private Map<RadialGradientPaintKey, String> A map of all the radial gradients used, and the corresponding id.(package private) Rectangle2DAn instance that is lazily instantiated in fillRect and then subsequently reused to avoid creating a lot of garbage.private RoundRectangle2DAn instance that is lazily instantiated in draw/fillRoundRect and then subsequently reused to avoid creating a lot of garbage.private final StringBuilderThe buffer that accumulates the SVG output.private StringThe shape rendering property to set for the SVG element.private booleanWhen true, plot paths hold curves rather than axis-aligned segments, so the globalshape-rendering:crispEdgesrule is overridden for them.private StrokeThe current stroke.private StringCached strokeStyle() result, invalidated on setStroke/setPaint/setComposite.private booleanTrue while the cached stroke style is current.private static final PatternRegex pattern for merging adjacent<text>elements that are split across separate<g>groups by the font class extraction step.private StringThe text rendering property for the SVG element.private StringConsole theme supplied by the caller, or null to infer it from the SVG.private AffineTransformThe current transform.private intThe number of decimal places to use when writing the matrix values for transformations.private final SVGUnitsThe units of the drawing area.private final intThe width of the drawing area.private doubleThe width of the SVG stroke to use when the user supplies a BasicStroke with a width of 0.0 (in this case the Java specification says "If width is set to 0.0f, the stroke is rendered as the thinnest possible line for the target device and the antialias hint setting.")Constructor Summary
ModifierConstructorDescriptionSVGGraphics2D(int width, int height) Creates a new instance with the specified width and height.SVGGraphics2D(int width, int height, StringBuilder sb) Creates a new instance with the specified width and height that will populate the supplied StringBuilder instance.SVGGraphics2D(int width, int height, SVGUnits units) Creates a new instance with the specified width and height in the given units.SVGGraphics2D(int width, int height, SVGUnits units, StringBuilder sb) Creates a new instance with the specified width and height that will populate the supplied StringBuilder instance.privateSVGGraphics2D(SVGGraphics2D parent) Creates a new instance that is a child of the supplied parent.Method Summary
Modifier and TypeMethodDescriptionvoidaddRenderingHints(Map<?, ?> hints) Adds all the supplied rendering hints.private voidA utility method that appends an optional element id if one is specified via the rendering hints.private voidappendThemeCSSDefs(SVGGraphics2D.Theme theme, StringBuilder defs) Appends theme-specific CSS rule overrides (major/minor grid colors, graph stroke) to the defs block.private voidappendThemeDefs(SVGGraphics2D.Theme theme, StringBuilder defs) Appends theme-specific linear gradient definitions to the SVG defs block.voidclearRect(int x, int y, int width, int height) Clears the specified rectangle by filling it with the current background color.voidClips to the intersection of the current clipping region and the specified shape.voidclipRect(int x, int y, int width, int height) Clips to the intersection of the current clipping region and the specified rectangle.private StringConsolidates consecutive SVG<line>elements that share a CSS class into a shared<g>group.voidcopyArea(int x, int y, int width, int height, int dx, int dy) This method does nothing.create()Creates a new graphics object that is a copy of this graphics object (except that it has not accumulated the drawing operations).private SVGGraphics2D.ThemedetectTheme(String svg) Detects the theme used in the SVG text.voiddispose()This method does nothing, there are no resources to dispose.voidDraws the specified shape with the currentpaintandstroke.voiddrawArc(int x, int y, int width, int height, int startAngle, int arcAngle) Draws an arc contained within the rectangle(x, y, width, height), starting atstartAngleand continuing througharcAngledegrees using the currentpaintandstroke.voiddrawGlyphVector(GlyphVector g, float x, float y) Draws the specified glyph vector at the location(x, y).voiddrawImage(BufferedImage img, BufferedImageOp op, int x, int y) Draws the image resulting from applying theBufferedImageOpto the specified image at the location(x, y).booleandrawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer) Draws part of an image (defined by the source rectangle(sx1, sy1, sx2, sy2)) into the destination rectangle(dx1, dy1, dx2, dy2).booleandrawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) Draws part of an image (defined by the source rectangle(sx1, sy1, sx2, sy2)) into the destination rectangle(dx1, dy1, dx2, dy2).booleandrawImage(Image img, int x, int y, int w, int h, Color bgcolor, ImageObserver observer) Draws an image to the rectangle(x, y, w, h)(scaling it if required), first filling the background with the specified color.booleandrawImage(Image img, int x, int y, int w, int h, ImageObserver observer) Draws the image into the rectangle defined by(x, y, w, h).booleandrawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) Draws an image at the location(x, y).booleandrawImage(Image img, int x, int y, ImageObserver observer) Draws an image at the location(x, y).booleandrawImage(Image img, AffineTransform xform, ImageObserver obs) Draws an image with the specified transform.voiddrawLine(int x1, int y1, int x2, int y2) Draws a line from(x1, y1)to(x2, y2)using the currentpaintandstroke.voiddrawOval(int x, int y, int width, int height) Draws an oval framed by the rectangle(x, y, width, height)using the currentpaintandstroke.voiddrawPolygon(int[] xPoints, int[] yPoints, int nPoints) Draws the specified polygon using the currentpaintandstroke.voiddrawPolyline(int[] xPoints, int[] yPoints, int nPoints) Draws the specified multi-segment line using the currentpaintandstroke.voiddrawRenderableImage(RenderableImage img, AffineTransform xform) Draws the renderable image.voiddrawRenderedImage(RenderedImage img, AffineTransform xform) Draws the rendered image.voiddrawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) Draws a rectangle with rounded corners using the currentpaintandstroke.voiddrawString(String str, float x, float y) Draws a string at(x, y).voiddrawString(String str, int x, int y) Draws a string at(x, y).voiddrawString(AttributedCharacterIterator iterator, float x, float y) Draws a string of attributed characters at(x, y).voiddrawString(AttributedCharacterIterator iterator, int x, int y) Draws a string of attributed characters at(x, y).private static StringexpandClipPath(String pathData, int padding) Expand a rectangular clip path by the given padding on all sides.voidFills the specified shape with the currentpaint.voidfillArc(int x, int y, int width, int height, int startAngle, int arcAngle) Fills an arc contained within the rectangle(x, y, width, height), starting atstartAngleand continuing througharcAngledegrees, using the currentpaint.voidfillOval(int x, int y, int width, int height) Fills an oval framed by the rectangle(x, y, width, height).voidfillPolygon(int[] xPoints, int[] yPoints, int nPoints) Fills the specified polygon using the currentpaint.voidfillRect(int x, int y, int width, int height) Fills the specified rectangle with the currentpaint.voidfillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) Fills a rectangle with rounded corners using the currentpaint.private StringgeomDP(double d) Formats a number for a geometry value.private floatgetAlpha()Returns the current alpha (transparency) in the range 0.0 to 1.0.Returns the background color.booleanReturns the flag that controls whether or not this object will observe theKEY_STROKE_CONTROLrendering hint.getClip()Returns the user clipping region.Returns the bounds of the user clipping region.private StringReturns a clip path reference for the current user clip.getColor()Returns the foreground color.private floatReturns the alpha value of the currentpaint, or1.0fif it is not an instance ofColor.Returns the current composite.Returns the prefix used for all keys in the DEFS element.Returns the device configuration associated with thisGraphics2D.Returns a new set containing the element IDs that have been used in output so far.Returns the prefix used to generate a filename for an image that is referenced from, rather than embedded in, the SVG element.Returns the suffix used to generate a filename for an image that is referenced from, rather than embedded in, the SVG element.getFont()Returns the current font used for drawing text.Returns the font mapper (an object that optionally maps font family names to alternates).Returns the font metrics for the specified font.Returns the font render context.Returns the font size units.intReturns the number of decimal places used to write the coordinates of geometrical shapes.intReturns the height for the SVG element, specified in the constructor.private StringgetLinearGradientElement(String id, GradientPaint paint) Returns an element to represent a linear gradient.private StringgetLinearGradientElement(String id, LinearGradientPaint paint) Returns an element to represent a linear gradient.getPaint()Returns the paint used to draw or fill shapes (or text).private byte[]getPNGBytes(Image img) Returns the bytes representing a PNG format image.private StringReturns an element to represent a radial gradient.getRenderingHint(RenderingHints.Key hintKey) Returns the current value for the specified hint.Returns a copy of the rendering hints.Returns the value of the 'shape-rendering' property that will be written to the SVG element.Returns the current stroke (used when drawing shapes).Returns an SVG document (this contains the content returned by thegetSVGElement()method, prepended with the required document header).Returns the SVG element that has been generated by calls to thisGraphics2Dimplementation.getSVGElement(String id) Returns the SVG element that has been generated by calls to thisGraphics2Dimplementation, giving it the specifiedid.getSVGElement(String id, boolean includeDimensions, ViewBox viewBox, PreserveAspectRatio preserveAspectRatio, MeetOrSlice meetOrSlice) Returns the SVG element that has been generated by calls to thisGraphics2Dimplementation, giving it the specifiedid.private StringReturns a fill style string based on the current paint and alpha settings.private StringReturns a string containing font style info.Returns the list of image elements that have been referenced in the SVG output but not embedded.private StringgetSVGPathData(Path2D path) Creates an SVG path string for the supplied Java2D path.private StringgetSVGPathDataRaw(Path2D path) Convert a Path2D to SVG path data without smoothing (original behavior).private StringConverts a transform to its SVG text.Returns the value of the 'text-rendering' property that will be written to the SVG element.Returns a copy of the current transform.intReturns the number of decimal places used to write the transformation matrices in the SVG output.getUnits()Returns the units for the width and height of the SVG element's viewport, as specified in the constructor.intgetWidth()Returns the width for the SVG element, specified in the constructor.doubleReturns the width to use for the SVG stroke when the AWT stroke specified has a zero width (the default value is0.1).(package private) static StringgroupLineRun(String run) Groups one run of consecutive self-closing<line>elements, breaking the run into sub-runs at every class change and wrapping each classed sub-run in a<g>of that class.booleanReturnstrueif the rectangle (in device space) intersects with the shape (the interior, ifonStrokeisfalse, otherwise the stroked outline of the shape).private StringpostProcessSvg(String svgRaw) Cleans up the generated SVG text.private StringregisterClip(Shape clip) Registers the clip so that we can later write out all the clip definitions in the DEFS element.private StringReturns a string representing the specified color in RGBA format.private StringrgbColorStr(Color c) Returns the SVG RGB color string for the specified color.voidrotate(double theta) Applies a rotation (anti-clockwise) about(0, 0).voidrotate(double theta, double x, double y) Applies a rotation (anti-clockwise) about(x, y).voidscale(double sx, double sy) Applies a scale transformation.private voidsetArc(int x, int y, int width, int height, int startAngle, int arcAngle) Sets the attributes of the reusableArc2Dobject that is used bydrawArc(int, int, int, int, int, int)andfillArc(int, int, int, int, int, int)methods.voidsetBackground(Color color) Sets the background color.voidsetCheckStrokeControlHint(boolean check) Sets the flag that controls whether or not this object will observe theKEY_STROKE_CONTROLrendering hint.voidsetClip(int x, int y, int width, int height) Sets the user clipping region to the specified rectangle.voidSets the user clipping region.voidSets the foreground color.voidsetComposite(Composite comp) Sets the composite (onlyAlphaCompositeis handled).voidsetDefsKeyPrefix(String prefix) Sets the prefix that will be used for all keys in the DEFS element.voidsetFilePrefix(String prefix) Sets the prefix used to generate a filename for any image that is referenced from the SVG element.voidsetFileSuffix(String suffix) Sets the suffix used to generate a filename for any image that is referenced from the SVG element.voidSets the font to be used for drawing text.voidsetFontMapper(FontMapper mapper) Sets the font mapper.voidsetFontSizeUnits(SVGUnits fontSizeUnits) Sets the font size units.voidsetGeometryDP(int dp) Sets the number of decimal places used to write the coordinates of geometrical shapes in the SVG output.voidsetGlowEnabled(boolean enabled) Enables or disables the glow effect for subsequent draw(Path2D) calls.private voidsetOval(int x, int y, int width, int height) Sets the attributes of the reusableEllipse2Dobject that is used by thedrawOval(int, int, int, int)andfillOval(int, int, int, int)methods.voidSets the paint used to draw or fill shapes (or text).voidDoes nothing in thisSVGGraphics2Dimplementation.private voidsetRect(int x, int y, int width, int height) Sets the attributes of the reusableRectangle2Dobject that is used by theGraphics.drawRect(int, int, int, int)andfillRect(int, int, int, int)methods.voidsetRenderingHint(RenderingHints.Key hintKey, Object hintValue) Sets the value for a hint.voidsetRenderingHints(Map<?, ?> hints) Sets the rendering hints to the specified collection.private voidsetRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) Sets the attributes of the reusableRoundRectangle2Dobject that is used by thedrawRoundRect(int, int, int, int, int, int)andfillRoundRect(int, int, int, int, int, int)methods.voidsetShapeRendering(String value) Sets the value of the 'shape-rendering' property that will be written to the SVG element.voidsetSmoothingEnabled(boolean enabled) Enables or disables smoothing antialiasing for plot paths.voidSets the stroke that will be used to draw shapes.voidsetTextRendering(String value) Sets the value of the 'text-rendering' property that will be written to the SVG element.voidsetThemeName(String name) Set the console theme, overriding inference from the SVG content.voidSets the transform.voidsetTransformDP(int dp) Sets the number of decimal places used to write the transformation matrices in the SVG output.voidsetXORMode(Color c) Does nothing in thisSVGGraphics2Dimplementation.voidsetZeroStrokeWidth(double width) Sets the width to use for the SVG stroke when the current AWT stroke has a width of 0.0.voidshear(double shx, double shy) Applies a shear transformation.private static StringstopOpacity(Color color) Thestop-opacityfor a gradient stop, or null when the stop is opaque.private StringReturns a stroke style string based on the current stroke and alpha settings.private StringReturns an SVG color string based on the current paint.(package private) static StringRetag the axis container lines so the theme's.axisrule supplies their stroke.voidApplies this transform to the existing transform by concatenating it.private StringtransformDP(double d) Formats a number for a transform value.voidtranslate(double tx, double ty) Applies the translation(tx, ty).voidtranslate(int tx, int ty) Applies the translation(tx, ty).private static StringwrapLineSubrun(String cssClass, CharSequence lines) Wraps one same-class sub-run in a group of that class, or emits it untouched when it carries no class - an unclassed sub-run would gain nothing from an empty wrapper.Methods inherited from class Graphics2D
draw3DRect, fill3DRectMethods inherited from class Graphics
create, drawBytes, drawChars, drawPolygon, drawRect, fillPolygon, getClipBounds, getFontMetrics, hitClip, toString
Field Details
CLIP_KEY_PREFIX
The prefix for keys used to identify clip paths.- See Also:
width
private final int widthThe width of the drawing area.height
private final int heightThe height of the drawing area.units
The units of the drawing area.shapeRendering
The shape rendering property to set for the SVG element. Permitted values are "auto", "crispEdges", "geometricPrecision" and "optimizeSpeed".textRendering
The text rendering property for the SVG element. Permitted values are "auto", "optimizeSpeed", "optimizeLegibility" and "geometricPrecision".fontSizeUnits
The font size units.hints
Rendering hints (see SVGHints).checkStrokeControlHint
private boolean checkStrokeControlHintA flag that controls whether or not the KEY_STROKE_CONTROL hint is checked.transformDP
private int transformDPThe number of decimal places to use when writing the matrix values for transformations.geometryDP
private int geometryDPThe number of decimal places to use when writing coordinates for geometrical shapes.sb
The buffer that accumulates the SVG output.defsKeyPrefix
A prefix for the keys used in the DEFS element. This can be used to ensure that the keys are unique when creating more than one SVG element for a single HTML page.gradientPaints
A map of all the gradients used, and the corresponding id. When generating the SVG file, all the gradient paints used must be defined in the defs element.linearGradientPaints
A map of all the linear gradients used, and the corresponding id. When generating the SVG file, all the linear gradient paints used must be defined in the defs element.radialGradientPaints
A map of all the radial gradients used, and the corresponding id. When generating the SVG file, all the radial gradient paints used must be defined in the defs element.clipPaths
filePrefix
The filename prefix for images that are referenced rather than embedded but don't have anhrefsupplied via theSVGHints.KEY_IMAGE_HREFhint.fileSuffix
The filename suffix for images that are referenced rather than embedded but don't have anhrefsupplied via theSVGHints.KEY_IMAGE_HREFhint.imageElements
A list of images that are referenced but not embedded in the SVG. After the SVG is generated, the caller can make use of this list to write PNG files if they don't already exist.clip
The user clip (can be null).clipRef
The reference for the current clip.transform
The current transform.paint
The paint used for filling.color
The color used for drawing text.composite
The alpha composite applied to the draws.stroke
The current stroke.strokeStyleCache
Cached strokeStyle() result, invalidated on setStroke/setPaint/setComposite.strokeStyleCacheValid
private boolean strokeStyleCacheValidTrue while the cached stroke style is current.fillStyleCache
Cached getSVGFillStyle() result, invalidated on setPaint/setComposite.fillStyleCacheValid
private boolean fillStyleCacheValidTrue while the cached fill style is current.glowEnabled
private boolean glowEnabledWhen true, the next draw(Path2D) emits a glow-filtered path before the original.smoothingEnabled
private boolean smoothingEnabledWhen true, plot paths hold curves rather than axis-aligned segments, so the globalshape-rendering:crispEdgesrule is overridden for them. Curves drawn with crisp edges render aliased, which defeats the point of smoothing them.Only paths are affected. In a graph body the grid and axes are emitted as
<line>elements and the background as<rect>, so a path in the body is always plot data; paths inside<clipPath>are unaffected because shape rendering does not apply to clipping.zeroStrokeWidth
private double zeroStrokeWidthThe width of the SVG stroke to use when the user supplies a BasicStroke with a width of 0.0 (in this case the Java specification says "If width is set to 0.0f, the stroke is rendered as the thinnest possible line for the target device and the antialias hint setting.")font
The last font that was set.fontRenderContext
The font render context. The fractional metrics flag solves the glyph positioning issue identified by Christoph Nahr: http://news.kynosarges.org/2014/06/28/glyph-positioning-in-jfreesvg-orsonpdf/fontMapper
Maps font family names to alternates (or leaves them unchanged).background
The background color, used by clearRect().fmImage
A hidden image used for font metrics.fmImageG2D
Graphics of the cached font metric image.line
An instance that is lazily instantiated in drawLine and then subsequently reused to avoid creating a lot of garbage.rect
Rectangle2D rectAn instance that is lazily instantiated in fillRect and then subsequently reused to avoid creating a lot of garbage.roundRect
An instance that is lazily instantiated in draw/fillRoundRect and then subsequently reused to avoid creating a lot of garbage.oval
An instance that is lazily instantiated in draw/fillOval and then subsequently reused to avoid creating a lot of garbage.arc
An instance that is lazily instantiated in draw/fillArc and then subsequently reused to avoid creating a lot of garbage.gradientPaintRef
If the current paint is an instance ofGradientPaint, this field will contain the reference id that is used in the DEFS element for that linear gradient.deviceConfiguration
The device configuration (this is lazily instantiated in the getDeviceConfiguration() method).elementIDs
DEFAULT_STROKE_CAP
SVG name of the default stroke cap.- See Also:
DEFAULT_STROKE_JOIN
SVG name of the default stroke join.- See Also:
FONT_CLASS_PATTERN
Regex pattern for extractingfont-familyandfont-sizefrom inlinestyleattributes and converting them to shorthand CSS classes. Matches anystyleattribute containingfont-family:(monospace|sans-serif)andfont-size:(\\d+)pxin any order relative to other properties, and captures the font family group (1) and size (2).TEXT_MERGE_PATTERN
Regex pattern for merging adjacent<text>elements that are split across separate<g>groups by the font class extraction step. Matches the closing</text></g>followed by an opening<g>with an optional CSS class and/orclip-path="url(#clip-2)", then another<text>. The replacement collapses the group boundary into a single<text>continuation.themeName
Console theme supplied by the caller, or null to infer it from the SVG.The inference reads the area fill colour, which only a filled-area graph emits, so a line-only graph (a combined multi-series plot) has nothing to read and used to be detected as CLASSIC, losing its gradient and themed text. The caller already knows the theme, so it is passed rather than guessed.
LINE_ELEMENT_REGEX
Matches a single self-closing<line>element with its trailing whitespace. The building block ofLINE_RUN_PATTERN; splitting a run needs the elements one by one so each one's class can be read.- See Also:
LINE_ELEMENT_PATTERN
Matches one self-closing<line>element, used to walk a run element by element.LINE_RUN_PATTERN
Matches consecutive runs of self-closing<line>elements. A run is one or more<line .../>elements with no other element types between them.LINE_CLASS_PATTERN
Extracts the CSS class name from aclass="..."attribute within a line run.
Constructor Details
SVGGraphics2D
public SVGGraphics2D(int width, int height) Creates a new instance with the specified width and height.- Parameters:
width- the width of the SVG element.height- the height of the SVG element.
SVGGraphics2D
Creates a new instance with the specified width and height in the given units.- Parameters:
width- the width of the SVG element.height- the height of the SVG element.units- the units for the width and height.
SVGGraphics2D
Creates a new instance with the specified width and height that will populate the supplied StringBuilder instance. This constructor is used by thecreate()method, but won't normally be called directly by user code.- Parameters:
width- the width of the SVG element.height- the height of the SVG element.sb- the string builder (nullnot permitted).
SVGGraphics2D
Creates a new instance with the specified width and height that will populate the supplied StringBuilder instance. This constructor is used by thecreate()method, but won't normally be called directly by user code.- Parameters:
width- the width of the SVG element.height- the height of the SVG element.units- the units for the width and height above (nullpermitted).sb- the string builder (nullnot permitted).
SVGGraphics2D
Creates a new instance that is a child of the supplied parent.- Parameters:
parent- the parent (nullnot permitted).
Method Details
setGlowEnabled
public void setGlowEnabled(boolean enabled) Enables or disables the glow effect for subsequent draw(Path2D) calls. When enabled, a filtered copy of the path is emitted before the original, creating a soft glow behind stroked lines.- Parameters:
enabled- true to enable glow path emission
setSmoothingEnabled
public void setSmoothingEnabled(boolean enabled) Enables or disables smoothing antialiasing for plot paths.- Parameters:
enabled- true when the plot paths contain curves
getWidth
public int getWidth()Returns the width for the SVG element, specified in the constructor. This value will be written to the SVG element returned by thegetSVGElement()method.- Returns:
- The width for the SVG element.
getHeight
public int getHeight()Returns the height for the SVG element, specified in the constructor. This value will be written to the SVG element returned by thegetSVGElement()method.- Returns:
- The height for the SVG element.
getUnits
Returns the units for the width and height of the SVG element's viewport, as specified in the constructor. The default value isnull).- Returns:
- The units (possibly
null).
getShapeRendering
Returns the value of the 'shape-rendering' property that will be written to the SVG element. The default value is "auto".- Returns:
- The shape rendering property.
setShapeRendering
Sets the value of the 'shape-rendering' property that will be written to the SVG element. Permitted values are "auto", "crispEdges", "geometricPrecision", "inherit" and "optimizeSpeed".- Parameters:
value- the new value.
getTextRendering
Returns the value of the 'text-rendering' property that will be written to the SVG element. The default value is "auto".- Returns:
- The text rendering property.
setTextRendering
Sets the value of the 'text-rendering' property that will be written to the SVG element. Permitted values are "auto", "optimizeSpeed", "optimizeLegibility" and "geometricPrecision".- Parameters:
value- the new value.
getCheckStrokeControlHint
public boolean getCheckStrokeControlHint()Returns the flag that controls whether or not this object will observe theKEY_STROKE_CONTROLrendering hint. The default value istrue.- Returns:
trueif theKEY_STROKE_CONTROLrendering hint is honoured, which it is by default.- See Also:
setCheckStrokeControlHint
public void setCheckStrokeControlHint(boolean check) Sets the flag that controls whether or not this object will observe theKEY_STROKE_CONTROLrendering hint. When enabled (the default), a hint to normalise strokes will write astroke-styleattribute with the valuecrispEdges.- Parameters:
check- the new flag value.- See Also:
getDefsKeyPrefix
Returns the prefix used for all keys in the DEFS element. The default value is"_"+ String.valueOf(System.nanoTime()).- Returns:
- The prefix string (never
null).
setDefsKeyPrefix
Sets the prefix that will be used for all keys in the DEFS element. If required, this must be set immediately after construction (before any content generation methods have been called).- Parameters:
prefix- the prefix (nullnot permitted).
getTransformDP
public int getTransformDP()Returns the number of decimal places used to write the transformation matrices in the SVG output. The default value is 6.Note that there is a separate attribute to control the number of decimal places for geometrical elements in the output (see
getGeometryDP()).- Returns:
- The number of decimal places.
- See Also:
setTransformDP
public void setTransformDP(int dp) Sets the number of decimal places used to write the transformation matrices in the SVG output. Values in the range 1 to 10 will be used to configure a formatter to that number of decimal places, for all other values we revert to the normalStringconversion ofdoubleprimitives (approximately 16 decimals places).Note that there is a separate attribute to control the number of decimal places for geometrical elements in the output (see
setGeometryDP(int)).- Parameters:
dp- the number of decimal places (normally 1 to 10).- See Also:
getGeometryDP
public int getGeometryDP()Returns the number of decimal places used to write the coordinates of geometrical shapes. The default value is 2.Note that there is a separate attribute to control the number of decimal places for transform matrices in the output (see
getTransformDP()).- Returns:
- The number of decimal places.
setGeometryDP
public void setGeometryDP(int dp) Sets the number of decimal places used to write the coordinates of geometrical shapes in the SVG output. Values in the range 1 to 10 will be used to configure a formatter to that number of decimal places, for all other values we revert to the normal String conversion of double primitives (approximately 16 decimals places).Note that there is a separate attribute to control the number of decimal places for transform matrices in the output (see
setTransformDP(int)).- Parameters:
dp- the number of decimal places (normally 1 to 10).
getFilePrefix
Returns the prefix used to generate a filename for an image that is referenced from, rather than embedded in, the SVG element.- Returns:
- The file prefix (never
null).
setFilePrefix
Sets the prefix used to generate a filename for any image that is referenced from the SVG element.- Parameters:
prefix- the new prefix (nullnot permitted).
getFileSuffix
Returns the suffix used to generate a filename for an image that is referenced from, rather than embedded in, the SVG element.- Returns:
- The file suffix (never
null).
setFileSuffix
Sets the suffix used to generate a filename for any image that is referenced from the SVG element.- Parameters:
suffix- the new prefix (nullnot permitted).
getZeroStrokeWidth
public double getZeroStrokeWidth()Returns the width to use for the SVG stroke when the AWT stroke specified has a zero width (the default value is0.1). In the Java specification forBasicStrokeit states "If width is set to 0.0f, the stroke is rendered as the thinnest possible line for the target device and the antialias hint setting." We don't have a means to implement that accurately since we must specify a fixed width.- Returns:
- the stroke width, in user units, used when the AWT stroke has zero width
setZeroStrokeWidth
public void setZeroStrokeWidth(double width) Sets the width to use for the SVG stroke when the current AWT stroke has a width of 0.0.- Parameters:
width- the new width (must be 0 or greater).
getDeviceConfiguration
Returns the device configuration associated with thisGraphics2D.- Specified by:
getDeviceConfigurationin classGraphics2D- Returns:
- The graphics configuration.
create
Creates a new graphics object that is a copy of this graphics object (except that it has not accumulated the drawing operations). Not sure yet when or why this would be useful when creating SVG output. Note that thefontMapperobject (getFontMapper()) is shared between the existing instance and the new one.getPaint
Returns the paint used to draw or fill shapes (or text). The default value isColor.BLACK.- Specified by:
getPaintin classGraphics2D- Returns:
- The paint (never
null). - See Also:
setPaint
Sets the paint used to draw or fill shapes (or text). Ifpaintis an instance ofColor, this method will also update the current color attribute (seegetColor()). If you passnullto this method, it does nothing (in accordance with the JDK specification).- Specified by:
setPaintin classGraphics2D- Parameters:
paint- the paint (nullis permitted but ignored).- See Also:
getColor
Returns the foreground color. This method exists for backwards compatibility in AWT, you should use thegetPaint()method.setColor
Sets the foreground color. This method exists for backwards compatibility in AWT, you should use thesetPaint(java.awt.Paint)method.getBackground
Returns the background color. The default value isColor.BLACK. This is used by theclearRect(int, int, int, int)method.- Specified by:
getBackgroundin classGraphics2D- Returns:
- The background color (possibly
null). - See Also:
setBackground
Sets the background color. This is used by theclearRect(int, int, int, int)method. The reference implementation allowsnullfor the background color so we allow that too (but for that case, the clearRect method will do nothing).- Specified by:
setBackgroundin classGraphics2D- Parameters:
color- the color (nullpermitted).- See Also:
getComposite
Returns the current composite.- Specified by:
getCompositein classGraphics2D- Returns:
- The current composite (never
null). - See Also:
setComposite
Sets the composite (onlyAlphaCompositeis handled).- Specified by:
setCompositein classGraphics2D- Parameters:
comp- the composite (nullnot permitted).- See Also:
getStroke
Returns the current stroke (used when drawing shapes).- Specified by:
getStrokein classGraphics2D- Returns:
- The current stroke (never
null). - See Also:
setStroke
Sets the stroke that will be used to draw shapes.- Specified by:
setStrokein classGraphics2D- Parameters:
s- the stroke (nullnot permitted).- See Also:
getRenderingHint
Returns the current value for the specified hint. See theSVGHintsclass for information about the hints that can be used withSVGGraphics2D.- Specified by:
getRenderingHintin classGraphics2D- Parameters:
hintKey- the hint key (nullpermitted, but the result will benullalso).- Returns:
- The current value for the specified hint (possibly
null). - See Also:
setRenderingHint
Sets the value for a hint. See theSVGHintsclass for information about the hints that can be used with this implementation.- Specified by:
setRenderingHintin classGraphics2D- Parameters:
hintKey- the hint key (nullnot permitted).hintValue- the hint value.- See Also:
getRenderingHints
Returns a copy of the rendering hints. Modifying the returned copy will have no impact on the state of thisGraphics2Dinstance.- Specified by:
getRenderingHintsin classGraphics2D- Returns:
- The rendering hints (never
null). - See Also:
setRenderingHints
Sets the rendering hints to the specified collection.- Specified by:
setRenderingHintsin classGraphics2D- Parameters:
hints- the new set of hints (nullnot permitted).- See Also:
addRenderingHints
Adds all the supplied rendering hints.- Specified by:
addRenderingHintsin classGraphics2D- Parameters:
hints- the hints (nullnot permitted).
appendOptionalElementIDFromHint
A utility method that appends an optional element id if one is specified via the rendering hints.- Parameters:
sb- the string builder (nullnot permitted).
draw
Draws the specified shape with the currentpaintandstroke. There is direct handling forLine2D,Rectangle2D,Ellipse2DandPath2D. All other shapes are mapped to aGeneralPathand then drawn (effectively asPath2Dobjects).- Specified by:
drawin classGraphics2D- Parameters:
s- the shape (nullnot permitted).- See Also:
fill
Fills the specified shape with the currentpaint. There is direct handling forRectangle2D,Ellipse2DandPath2D. All other shapes are mapped to aGeneralPathand then filled.- Specified by:
fillin classGraphics2D- Parameters:
s- the shape (nullnot permitted).- See Also:
getSVGPathData
getSVGPathDataRaw
getAlpha
private float getAlpha()Returns the current alpha (transparency) in the range 0.0 to 1.0. If the current composite is anAlphaCompositewe read the alpha value from there, otherwise this method returns 1.0.- Returns:
- The current alpha (transparency) in the range 0.0 to 1.0.
svgColorStr
Returns an SVG color string based on the current paint. To handleGradientPaintwe rely on thesetPaint()method having set thegradientPaintRefattribute.- Returns:
- An SVG color string.
rgbColorStr
rgbaColorStr
strokeStyle
Returns a stroke style string based on the current stroke and alpha settings.- Returns:
- A stroke style string.
getColorAlpha
private float getColorAlpha()Returns the alpha value of the currentpaint, or1.0fif it is not an instance ofColor.- Returns:
- The alpha value (in the range
0.0to1.0.
getSVGFillStyle
Returns a fill style string based on the current paint and alpha settings.- Returns:
- A fill style string.
getFont
setFont
getFontMapper
Returns the font mapper (an object that optionally maps font family names to alternates). The default mapper will convert Java logical font names to the equivalent SVG generic font name, and leave all other font names unchanged.- Returns:
- The font mapper (never
null). - See Also:
setFontMapper
Sets the font mapper.- Parameters:
mapper- the font mapper (nullnot permitted).
getFontSizeUnits
Returns the font size units. The default value isSVGUnits.PX.- Returns:
- The font size units.
setFontSizeUnits
Sets the font size units. In general, if this method is used it should be called immediately after theSVGGraphics2Dinstance is created and before any content is generated.- Parameters:
fontSizeUnits- the font size units (nullnot permitted).
getSVGFontStyle
Returns a string containing font style info.- Returns:
- A string containing font style info.
getFontMetrics
Returns the font metrics for the specified font.- Specified by:
getFontMetricsin classGraphics- Parameters:
f- the font to measure; the metrics come from an offscreen 10x10 image.- Returns:
- The font metrics.
getFontRenderContext
Returns the font render context.- Specified by:
getFontRenderContextin classGraphics2D- Returns:
- The font render context (never
null).
drawString
Draws a string at(x, y). The start of the text at the baseline level will be aligned with the(x, y)point.
Note that you can make use of theSVGHints.KEY_TEXT_RENDERINGhint when drawing strings (this is completely optional though).- Specified by:
drawStringin classGraphics2D- Parameters:
str- the string (nullnot permitted).x- the user-space x-coordinate of the text baseline origin.y- the user-space y-coordinate of the text baseline origin.- See Also:
drawString
Draws a string at(x, y). The start of the text at the baseline level will be aligned with the(x, y)point.
Note that you can make use of theSVGHints.KEY_TEXT_RENDERINGhint when drawing strings (this is completely optional though).- Specified by:
drawStringin classGraphics2D- Parameters:
str- the string (nullnot permitted).x- the user-space x-coordinate of the text baseline origin.y- the user-space y-coordinate of the text baseline origin.
drawString
Draws a string of attributed characters at(x, y). The call is delegated todrawString(AttributedCharacterIterator, float, float).- Specified by:
drawStringin classGraphics2D- Parameters:
iterator- an iterator for the characters.x- the user-space x-coordinate of the text baseline origin.y- the user-space y-coordinate of the text baseline origin.
drawString
Draws a string of attributed characters at(x, y).- Specified by:
drawStringin classGraphics2D- Parameters:
iterator- an iterator over the characters (nullnot permitted).x- the user-space x-coordinate of the text baseline origin.y- the user-space y-coordinate of the text baseline origin.
drawGlyphVector
Draws the specified glyph vector at the location(x, y).- Specified by:
drawGlyphVectorin classGraphics2D- Parameters:
g- the glyph vector (nullnot permitted).x- the user-space x-coordinate at which to place the glyph outline origin.y- the user-space y-coordinate at which to place the glyph outline origin.
translate
public void translate(int tx, int ty) Applies the translation(tx, ty). This call is delegated totranslate(double, double).- Specified by:
translatein classGraphics2D- Parameters:
tx- the horizontal translation in user units, applied to later drawing.ty- the vertical translation in user units, applied to later drawing.- See Also:
translate
public void translate(double tx, double ty) Applies the translation(tx, ty).- Specified by:
translatein classGraphics2D- Parameters:
tx- the horizontal translation in user units, applied to later drawing.ty- the vertical translation in user units, applied to later drawing.
rotate
public void rotate(double theta) Applies a rotation (anti-clockwise) about(0, 0).- Specified by:
rotatein classGraphics2D- Parameters:
theta- the rotation angle (in radians).
rotate
public void rotate(double theta, double x, double y) Applies a rotation (anti-clockwise) about(x, y).- Specified by:
rotatein classGraphics2D- Parameters:
theta- the rotation angle (in radians).x- the user-space x-coordinate of the centre of rotation.y- the user-space y-coordinate of the centre of rotation.
scale
public void scale(double sx, double sy) Applies a scale transformation.- Specified by:
scalein classGraphics2D- Parameters:
sx- the x-scaling factor.sy- the y-scaling factor.
shear
public void shear(double shx, double shy) Applies a shear transformation. This is equivalent to the following call to thetransformmethod:transform(AffineTransform.getShearInstance(shx, shy));
- Specified by:
shearin classGraphics2D- Parameters:
shx- the x-shear factor.shy- the y-shear factor.
transform
Applies this transform to the existing transform by concatenating it.- Specified by:
transformin classGraphics2D- Parameters:
t- the transform (nullnot permitted).
getTransform
Returns a copy of the current transform.- Specified by:
getTransformin classGraphics2D- Returns:
- A copy of the current transform (never
null). - See Also:
setTransform
Sets the transform.- Specified by:
setTransformin classGraphics2D- Parameters:
t- the new transform (nullpermitted, resets to the identity transform).- See Also:
hit
Returnstrueif the rectangle (in device space) intersects with the shape (the interior, ifonStrokeisfalse, otherwise the stroked outline of the shape).- Specified by:
hitin classGraphics2D- Parameters:
rect- a rectangle (in device space).s- the shape to test; the current transform is applied to it first.onStroke- test the stroked outline only?- Returns:
trueif the rectangle intersects the transformed shape, testing the stroked outline whenonStrokeistrueand the interior otherwise.
setPaintMode
public void setPaintMode()Does nothing in thisSVGGraphics2Dimplementation.- Specified by:
setPaintModein classGraphics
setXORMode
Does nothing in thisSVGGraphics2Dimplementation.- Specified by:
setXORModein classGraphics- Parameters:
c- the colour to XOR with - ignored, SVG output has no XOR mode
getClipBounds
Returns the bounds of the user clipping region.- Specified by:
getClipBoundsin classGraphics- Returns:
- The clip bounds (possibly
null). - See Also:
getClip
setClip
registerClip
transformDP
Formats a number for a transform value.- Parameters:
d- the value to format- Returns:
- the formatted text
stopOpacity
Thestop-opacityfor a gradient stop, or null when the stop is opaque.Deliberately not
transformDP(double): that rounds totransformDPdecimal places, which is zero by default because it is a coordinate setting. Alpha needs three places - a theme's fills run from #08 to #c0, i.e. 0.03 to 0.75, and rounding those to whole numbers wrotestop-opacity="0.", which is not a valid number and renders the stop as fully transparent. Every translucent gradient stop therefore vanished while a flat fill of the same colour, which goes through the separate opacity formatter, came out correctly.Formatted in
Locale.USso a locale with a comma decimal separator cannot produce an unparseable attribute, and trailing zeroes are trimmed so a fully opaque stop written by a caller that did not guard would still read as1.- Parameters:
color- the stop's colour- Returns:
- the opacity as a decimal string, or null when the colour is fully opaque
geomDP
Formats a number for a geometry value.- Parameters:
d- the value to format- Returns:
- the formatted text
getSVGTransform
Converts a transform to its SVG text.- Parameters:
t- the transform to convert- Returns:
- the SVG transform text
clip
Clips to the intersection of the current clipping region and the specified shape.The pre-JDK 17 API specification said this method accepts a
nullargument; JDK-6206189 corrected the spec — a null argument throws NPE.- Specified by:
clipin classGraphics2D- Parameters:
s- the clip shape (nullnot permitted).
clipRect
public void clipRect(int x, int y, int width, int height) Clips to the intersection of the current clipping region and the specified rectangle.- Specified by:
clipRectin classGraphics- Parameters:
x- the user-space x-coordinate of the left edge of the rectangle.y- the user-space y-coordinate of the top edge of the rectangle.width- the horizontal extent of the rectangle to intersect with the current clip.height- the vertical extent of that rectangle.
setClip
public void setClip(int x, int y, int width, int height) Sets the user clipping region to the specified rectangle.drawLine
public void drawLine(int x1, int y1, int x2, int y2) Draws a line from(x1, y1)to(x2, y2)using the currentpaintandstroke.fillRect
public void fillRect(int x, int y, int width, int height) Fills the specified rectangle with the currentpaint.clearRect
public void clearRect(int x, int y, int width, int height) Clears the specified rectangle by filling it with the current background color. If the background color isnull, this method will do nothing.- Specified by:
clearRectin classGraphics- Parameters:
x- the user-space x-coordinate of the left edge of the region.y- the user-space y-coordinate of the top edge of the region.width- the horizontal extent of the region to clear with the background color.height- the vertical extent of that region.- See Also:
drawRoundRect
public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) Draws a rectangle with rounded corners using the currentpaintandstroke.- Specified by:
drawRoundRectin classGraphics- Parameters:
x- the user-space x-coordinate of the left edge of the bounding rectangle.y- the user-space y-coordinate of the top edge of the bounding rectangle.width- the horizontal extent of the bounding rectangle, the rounded corners included.height- the vertical extent of that bounding rectangle.arcWidth- the horizontal diameter of each corner arc, not its radius.arcHeight- the vertical diameter of each corner arc, not its radius.- See Also:
fillRoundRect
public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) Fills a rectangle with rounded corners using the currentpaint.- Specified by:
fillRoundRectin classGraphics- Parameters:
x- the user-space x-coordinate of the left edge of the bounding rectangle.y- the user-space y-coordinate of the top edge of the bounding rectangle.width- the horizontal extent of the bounding rectangle, the rounded corners included.height- the vertical extent of that bounding rectangle.arcWidth- the horizontal diameter of each corner arc, not its radius.arcHeight- the vertical diameter of each corner arc, not its radius.- See Also:
drawOval
public void drawOval(int x, int y, int width, int height) Draws an oval framed by the rectangle(x, y, width, height)using the currentpaintandstroke.- Specified by:
drawOvalin classGraphics- Parameters:
x- the user-space x-coordinate of the left edge of the oval's frame.y- the user-space y-coordinate of the top edge of the oval's frame.width- the horizontal extent of the frame the oval is inscribed in, not a radius.height- the vertical extent of that frame.- See Also:
fillOval
public void fillOval(int x, int y, int width, int height) Fills an oval framed by the rectangle(x, y, width, height).- Specified by:
fillOvalin classGraphics- Parameters:
x- the user-space x-coordinate of the left edge of the oval's frame.y- the user-space y-coordinate of the top edge of the oval's frame.width- the horizontal extent of the frame the oval is inscribed in, not a radius.height- the vertical extent of that frame.- See Also:
drawArc
public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) Draws an arc contained within the rectangle(x, y, width, height), starting atstartAngleand continuing througharcAngledegrees using the currentpaintandstroke.- Specified by:
drawArcin classGraphics- Parameters:
x- the user-space x-coordinate of the left edge of the arc's frame.y- the user-space y-coordinate of the top edge of the arc's frame.width- the horizontal extent of the frame the arc is inscribed in, not a radius.height- the vertical extent of that frame.startAngle- the start angle in degrees, 0 = 3 o'clock.arcAngle- the angle (anticlockwise) in degrees.- See Also:
fillArc
public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) Fills an arc contained within the rectangle(x, y, width, height), starting atstartAngleand continuing througharcAngledegrees, using the currentpaint.- Specified by:
fillArcin classGraphics- Parameters:
x- the user-space x-coordinate of the left edge of the arc's frame.y- the user-space y-coordinate of the top edge of the arc's frame.width- the horizontal extent of the frame the arc is inscribed in, not a radius.height- the vertical extent of that frame.startAngle- the start angle in degrees, 0 = 3 o'clock.arcAngle- the angle (anticlockwise) in degrees.- See Also:
drawPolyline
public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) Draws the specified multi-segment line using the currentpaintandstroke.- Specified by:
drawPolylinein classGraphics- Parameters:
xPoints- the user-space x-coordinates of the vertices; only the firstnPointsentries are readyPoints- the user-space y-coordinates of the vertices; only the firstnPointsentries are readnPoints- the number of points to use for the polyline.
drawPolygon
public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) Draws the specified polygon using the currentpaintandstroke.- Specified by:
drawPolygonin classGraphics- Parameters:
xPoints- the user-space x-coordinates of the vertices; only the firstnPointsentries are readyPoints- the user-space y-coordinates of the vertices; only the firstnPointsentries are readnPoints- the number of points to use for the polygon.- See Also:
fillPolygon
public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) Fills the specified polygon using the currentpaint.- Specified by:
fillPolygonin classGraphics- Parameters:
xPoints- the user-space x-coordinates of the vertices; only the firstnPointsentries are readyPoints- the user-space y-coordinates of the vertices; only the firstnPointsentries are readnPoints- the number of points to use for the polygon.- See Also:
getPNGBytes
Returns the bytes representing a PNG format image.- Parameters:
img- the image to encode (nullnot permitted).- Returns:
- The bytes representing a PNG format image.
drawImage
Draws an image at the location(x, y). Note that theobserveris ignored.- Specified by:
drawImagein classGraphics- Parameters:
img- the image (nullpermitted...method will do nothing).x- the user-space x-coordinate of the top left corner of the image.y- the user-space y-coordinate of the top left corner of the image.observer- an ImageObserver; SVG output is synchronous, so it is never notified.- Returns:
trueif there is no more drawing to be done.
drawImage
Draws the image into the rectangle defined by(x, y, w, h). Note that theobserveris ignored (it is not useful in this context).- Specified by:
drawImagein classGraphics- Parameters:
img- the image (nullpermitted...draws nothing).x- the user-space x-coordinate of the left edge of the target rectangle.y- the user-space y-coordinate of the top edge of the target rectangle.w- the width of the target rectangle, which the image is scaled to fit.h- the height of the target rectangle, which the image is scaled to fit.observer- an ImageObserver; SVG output is synchronous, so it is never notified.- Returns:
trueif there is no more drawing to be done.
drawImage
Draws an image at the location(x, y). Note that theobserveris ignored.- Specified by:
drawImagein classGraphics- Parameters:
img- the image (nullpermitted...draws nothing).x- the user-space x-coordinate of the top left corner of the image.y- the user-space y-coordinate of the top left corner of the image.bgcolor- the background color (nullpermitted).observer- an ImageObserver; SVG output is synchronous, so it is never notified.- Returns:
trueif there is no more drawing to be done.
drawImage
public boolean drawImage(Image img, int x, int y, int w, int h, Color bgcolor, ImageObserver observer) Draws an image to the rectangle(x, y, w, h)(scaling it if required), first filling the background with the specified color. Note that theobserveris ignored.- Specified by:
drawImagein classGraphics- Parameters:
img- the image to scale into the target rectangle.x- the user-space x-coordinate of the left edge of the target rectangle.y- the user-space y-coordinate of the top edge of the target rectangle.w- the width of the target rectangle, which the image is scaled to fit.h- the height of the target rectangle, which the image is scaled to fit.bgcolor- the background color (nullpermitted).observer- an ImageObserver; SVG output is synchronous, so it is never notified.- Returns:
trueif the image is drawn.
drawImage
public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) Draws part of an image (defined by the source rectangle(sx1, sy1, sx2, sy2)) into the destination rectangle(dx1, dy1, dx2, dy2). Note that theobserveris ignored.- Specified by:
drawImagein classGraphics- Parameters:
img- the image the source rectangle is read from.dx1- the x-coordinate for the top left of the destination.dy1- the y-coordinate for the top left of the destination.dx2- the x-coordinate for the bottom right of the destination.dy2- the y-coordinate for the bottom right of the destination.sx1- the x-coordinate for the top left of the source.sy1- the y-coordinate for the top left of the source.sx2- the x-coordinate for the bottom right of the source.sy2- the y-coordinate for the bottom right of the source.- Returns:
trueif the image is drawn.
drawImage
public boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer) Draws part of an image (defined by the source rectangle(sx1, sy1, sx2, sy2)) into the destination rectangle(dx1, dy1, dx2, dy2). The destination rectangle is first cleared by filling it with the specifiedbgcolor. Note that theobserveris ignored.- Specified by:
drawImagein classGraphics- Parameters:
img- the image the source rectangle is read from.dx1- the x-coordinate for the top left of the destination.dy1- the y-coordinate for the top left of the destination.dx2- the x-coordinate for the bottom right of the destination.dy2- the y-coordinate for the bottom right of the destination.sx1- the x-coordinate for the top left of the source.sy1- the y-coordinate for the top left of the source.sx2- the x-coordinate for the bottom right of the source.sy2- the y-coordinate for the bottom right of the source.bgcolor- the background color (nullpermitted).observer- an ImageObserver; SVG output is synchronous, so it is never notified.- Returns:
trueif the image is drawn.
drawRenderedImage
Draws the rendered image. Ifimgisnullthis method does nothing.- Specified by:
drawRenderedImagein classGraphics2D- Parameters:
img- the image (nullpermitted).xform- the transform mapping image space to user space (nullpermitted).
drawRenderableImage
Draws the renderable image.- Specified by:
drawRenderableImagein classGraphics2D- Parameters:
img- the renderable image.xform- the transform mapping image space to user space (nullpermitted).
drawImage
Draws an image with the specified transform. Note that theobserveris ignored.- Specified by:
drawImagein classGraphics2D- Parameters:
img- the image to draw (nullpermitted...draws nothing).xform- the transform (nullpermitted).obs- the image observer (ignored).- Returns:
trueif the image is drawn.
drawImage
Draws the image resulting from applying theBufferedImageOpto the specified image at the location(x, y).- Specified by:
drawImagein classGraphics2D- Parameters:
img- the image to filter and draw.op- the operation (nullpermitted).x- the user-space x-coordinate of the top left corner of the filtered image.y- the user-space y-coordinate of the top left corner of the filtered image.
copyArea
public void copyArea(int x, int y, int width, int height, int dx, int dy) This method does nothing. The operation assumes that the output is in bitmap form, which is not the case for SVG, so we silently ignore this method call.dispose
setThemeName
Set the console theme, overriding inference from the SVG content.- Parameters:
name- one of DARK, LIGHT, MIDNIGHT or CLASSIC; null restores inference
detectTheme
Detects the theme used in the SVG text.- Parameters:
svg- the SVG text to inspect- Returns:
- the theme found
appendThemeDefs
Appends theme-specific linear gradient definitions to the SVG defs block. Classic theme has no gradient fill (uses inline RGB colors).- Parameters:
theme- the detected theme.defs- the defs StringBuilder to append to.
appendThemeCSSDefs
Appends theme-specific CSS rule overrides (major/minor grid colors, graph stroke) to the defs block. These are appended inside the<style>element.- Parameters:
theme- the detected theme.defs- the defs StringBuilder containing the base<style>block.
tagAxis
Retag the axis container lines so the theme's.axisrule supplies their stroke.Package-visible and static so the rule can be tested against the exact markup the serialiser produces, at every position the stroke width can occupy. Three separate defects lived in this one line: it was written for a
<g>when the axis arrives as a bare<line>; it assumed the width led the style attribute; and its terminator consumed the closing quote when the width came last.- Parameters:
svg- the generated SVG- Returns:
- the SVG with the axis lines tagged
postProcessSvg
consolidateSvgGroups
Consolidates consecutive SVG<line>elements that share a CSS class into a shared<g>group. For example, 47 consecutive<line class="dash minor"/>elements become a single<g class="dash minor">wrapper. Text consolidation is handled by the existing font class extraction and text merge steps inpostProcessSvg.Each run is split wherever the class changes, so a line never inherits a class it was not drawn with. See
groupLineRun(String)for why that matters.- Parameters:
svg- the post-processed SVG content.- Returns:
- the SVG with consolidated line groups.
groupLineRun
Groups one run of consecutive self-closing<line>elements, breaking the run into sub-runs at every class change and wrapping each classed sub-run in a<g>of that class. Sub-runs carrying no class are emitted unchanged.This used to take the first class in the run, strip every line's own class and wrap the whole run in it. The axis container lines are tagged
class="axis"bytagAxis(String)and drawn straight after the value-axis gridlines, so a classed gridline landing in front of them with no intervening<text>- which is what the MRTG-style value axis does, since it draws each label and its gridline together - handed the whole run to the gridline's class, and the axis was restyled as a dashed gridline instead of the solid bounding box. Splitting at the class boundary keeps each line's own class, so the outcome no longer depends on the order elements happen to serialise in.- Parameters:
run- a run of one or more adjacent<line .../>elements- Returns:
- the run with same-class groups collapsed; never null
wrapLineSubrun
Wraps one same-class sub-run in a group of that class, or emits it untouched when it carries no class - an unclassed sub-run would gain nothing from an empty wrapper.- Parameters:
cssClass- the class shared by every line inlines, or null for nonelines- the sub-run's lines, in document order- Returns:
- the wrapped or unchanged sub-run; never null
getSVGElement
Returns the SVG element that has been generated by calls to thisGraphics2Dimplementation.- Returns:
- The SVG element.
getSVGElement
Returns the SVG element that has been generated by calls to thisGraphics2Dimplementation, giving it the specifiedid. Ifidisnull, the element will have noidattribute.- Parameters:
id- the element id (nullpermitted).- Returns:
- A string containing the SVG element.
getSVGElement
public String getSVGElement(String id, boolean includeDimensions, ViewBox viewBox, PreserveAspectRatio preserveAspectRatio, MeetOrSlice meetOrSlice) Returns the SVG element that has been generated by calls to thisGraphics2Dimplementation, giving it the specifiedid. Ifidisnull, the element will have noidattribute. This method also allows for aviewBoxto be defined, along with the settings that handle scaling.- Parameters:
id- the element id (nullpermitted).includeDimensions- include the width and height attributes?viewBox- the view box specification (ifnullthen noviewBoxattribute will be defined).preserveAspectRatio- the value of thepreserveAspectRatioattribute (ifnullthen not attribute will be defined).meetOrSlice- the value of the meetOrSlice attribute.- Returns:
- A string containing the SVG element.
getSVGDocument
Returns an SVG document (this contains the content returned by thegetSVGElement()method, prepended with the required document header).- Returns:
- An SVG document.
getSVGImages
Returns the list of image elements that have been referenced in the SVG output but not embedded. If the image files don't already exist, you can use this list as the basis for creating the image files.- Returns:
- The list of image elements.
- See Also:
getElementIDs
getLinearGradientElement
Returns an element to represent a linear gradient. All the linear gradients that are used get written to the DEFS element in the SVG.- Parameters:
id- the reference id.paint- theGradientPaintsupplying the two points, stops and fractions.- Returns:
- The SVG element.
getLinearGradientElement
Returns an element to represent a linear gradient. All the linear gradients that are used get written to the DEFS element in the SVG.- Parameters:
id- the reference id.paint- theLinearGradientPaintsupplying the two points, stops and fractions.- Returns:
- The SVG element.
getRadialGradientElement
Returns an element to represent a radial gradient. All the radial gradients that are used get written to the DEFS element in the SVG.- Parameters:
id- the reference id.rgp- the radial gradient.- Returns:
- The SVG element.
getClipPathRef
Returns a clip path reference for the current user clip. This is written out on all SVG elements that draw or fill shapes or text.- Returns:
- A clip path reference.
expandClipPath
Expand a rectangular clip path by the given padding on all sides. Handles the format: d="M x y l w 0 l 0 h l -w 0 l 0 -h Z"- Parameters:
pathData- the full SVG path data attribute (d="...")padding- pixels to expand on each side- Returns:
- expanded path data attribute, or original if format unrecognized
setRect
private void setRect(int x, int y, int width, int height) Sets the attributes of the reusableRectangle2Dobject that is used by theGraphics.drawRect(int, int, int, int)andfillRect(int, int, int, int)methods.- Parameters:
x- the user-space x-coordinate of the left edge of the rectangle.y- the user-space y-coordinate of the top edge of the rectangle.width- the horizontal extent to store in the reusable rectangle.height- the vertical extent to store in the reusable rectangle.
setRoundRect
private void setRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) Sets the attributes of the reusableRoundRectangle2Dobject that is used by thedrawRoundRect(int, int, int, int, int, int)andfillRoundRect(int, int, int, int, int, int)methods.- Parameters:
x- the user-space x-coordinate of the left edge of the bounding rectangle.y- the user-space y-coordinate of the top edge of the bounding rectangle.width- the horizontal extent of the bounding rectangle, the rounded corners included.height- the vertical extent of that bounding rectangle.arcWidth- the arc width.arcHeight- the arc height.
setArc
private void setArc(int x, int y, int width, int height, int startAngle, int arcAngle) Sets the attributes of the reusableArc2Dobject that is used bydrawArc(int, int, int, int, int, int)andfillArc(int, int, int, int, int, int)methods.- Parameters:
x- the user-space x-coordinate of the left edge of the arc's frame.y- the user-space y-coordinate of the top edge of the arc's frame.width- the horizontal extent of the frame the arc is inscribed in, not a radius.height- the vertical extent of that frame.startAngle- the start angle in degrees, 0 = 3 o'clock.arcAngle- the angle (anticlockwise) in degrees.
setOval
private void setOval(int x, int y, int width, int height) Sets the attributes of the reusableEllipse2Dobject that is used by thedrawOval(int, int, int, int)andfillOval(int, int, int, int)methods.- Parameters:
x- the user-space x-coordinate of the left edge of the oval's frame.y- the user-space y-coordinate of the top edge of the oval's frame.width- the horizontal extent of the frame the oval is inscribed in, not a radius.height- the vertical extent of that frame.