SVG Salamander

repository·master·Indexed 41 days ago

https://github.com/blackears/svgsalamander

A lightweight, fast SVG engine for Java optimized for game developers and artists. It provides direct scene graph access, coordinate picking, and efficient rendering to Graphics2D or BufferedImage contexts. Features include support for animations, an Ant task for converting SVGs to images, and Swing components like SVGPanel and SVGIcon. Version 1.1.5.5 is available via Maven as the svg-salamander artifact.

Tokens
2.5K
Snippets
8
Records
11
Agent score
1%

What's inside SVG Salamander

  1. Key features of SVG Salamander

    master

    SVG Salamander is a lightweight SVG engine for Java designed for speed and ease of integration, particularly for games and 2D graphics. Key capabilities include:

    • Lightweight: Smaller footprint than Batik and distributed as a single JAR.
    • Direct Scene Graph Access: Manipulate the SVG tree directly using Java commands.
    • Shape Indexing: Easily access an index of all named shapes in the SVG graph.
    • Coordinate Picking: Pick shapes based on (x, y) coordinates, useful for implementing mouse-driven graphical buttons.
    • Efficient Rendering: Supports clip region sensitivity for fast partial updates (e.g., efficient camera panning) and renders to any Graphics2D or BufferedImage context.
    • Flexible Input: Read SVG from an InputStream (allowing for dynamic XSLT transformations) or via URIs (supporting remote server imports).
    • Simplified Loading: The SVGIcon class simplifies the process of loading and drawing images to the screen.
    • Ant Integration: Includes an Ant task for converting SVG to images within Ant scripts.
  2. How to edit SVG attributes (Style vs. Presentation)

    master

    SVG Salamander distinguishes between two types of attributes:

    • Style attributes (CSS): Defined within the style attribute (e.g., fill:red). Use AnimationElement.AT_CSS.
    • Presentation attributes (XML): Defined as direct attributes (e.g., fill="red"). Use AnimationElement.AT_XML.

    Key Operations:

    • Check existence: svgElement.hasAttribute("name", type)
    • Add attribute: svgElement.addAttribute("name", type, "value"). Warning: Throws RuntimeException if the attribute already exists.
    • Set attribute: svgElement.setAttribute("name", type, "value"). Warning: Throws exception if the element does not exist.
    • Get value: Create a StyleAttribute object, set its name, and call svgElement.getStyle(style). Use style.getDoubleValue() (or other type methods) to retrieve the value.

    Precedence: Style attributes (AT_CSS) override presentation attributes (AT_XML). To bypass inheritance and get only the local value, use getStyleAbsolute() or getPresAbsolute().

    // Adding a style attribute
    svgElement.addAttribute("fill-opacity", AnimationElement.AT_CSS, "0.5");
    
    // Setting a presentation attribute
    svgElement.setAttribute("x", AnimationElement.AT_XML, "0.5");
    
    // Getting a value
    StyleAttribute style = new StyleAttribute();
    style.setName("fill");
    svgElement.getStyle(style);
    double value = style.getDoubleValue();
  3. Basic workflow for rendering SVG with SVG Salamander

    master

    To render an SVG using SVG Salamander, follow these steps:

    1. Create an SVGUniverse: This acts as the container for your loaded SVG files.
    2. Load the SVG: Use universe.loadSVG() to load a file into memory. If the SVG references other files, they are loaded automatically.
    3. Get the Diagram: Call universe.getDiagram() to obtain an SVGDiagram object.
    4. Prepare Graphics2D: Create a Graphics2D object. Ensure you either set a clip area on the Graphics2D or call diagram.setIgnoringClipHeuristic(true) to ensure shapes outside the clip area are still rendered.
    5. Render: Call diagram.render() to draw the SVG to the Graphics2D object.

    To handle animations or time-based changes, use universe.setCurTime() followed by universe.updateTime(), then call diagram.render() again to draw the new frame.

    SVGUniverse universe = new SVGUniverse();
    universe.loadSVG("path/to/file.svg");
    SVGDiagram diagram = universe.getDiagram();
    
    // In your paint component or rendering loop:
    Graphics2D g2d = (Graphics2D) g;
    // Optional: diagram.setIgnoringClipHeuristic(true);
    diagram.render(g2d);
  4. Update SVG elements after attribute changes

    master

    When you modify attributes that affect the shape of an element (like r for a circle or cx/cy for position), you must call updateTime(float timeInSeconds) on the element or one of its ancestors to reflect the changes in the internal state. For non-animated documents, you can pass any value (e.g., 0f).

    To update the entire document at once, call svgDiagram.updateTime().

    circle.setAttribute("r", AnimationElement.AT_XML, "10");
    circle.updateTime(0f); 
  5. Add and remove children in the SVG tree

    master

    SVG Salamander follows a scene graph model.

    To add a child:

    1. Create the new element instance.
    2. Set its attributes.
    3. Use parent.loaderAddChild(null, child) to attach it to a parent (e.g., a Group).
    4. Call parent.updateTime(0.0) to ensure the change propagates through the tree.

    To remove a child: Call parent.removeChild(child) on an element that supports children (like a Group).

    // Adding
    Group group = (Group)diagram.getElement("parentGroup"); 
    Circle circle = new Circle(); 
    circle.addAttribute("cx", AnimationElement.AT_XML, "80");
    group.loaderAddChild(null, circle);
    group.updateTime(0.0);
    
    // Removing
    Group group = (Group)diagram.getElement("circleGroup"); 
    Circle circle = (Circle)diagram.getElement("circleToRemove"); 
    group.removeChild(circle);
  6. Install SVG Salamander via Maven

    master

    To include SVG Salamander in your Java project, add the svg-salamander dependency to your pom.xml file. Note that as of version 1.1.5.1, the artifact ID has been renamed from svgSalamander to svg-salamander to follow community standards.

    <dependency>
      <groupId>io.github.blackears</groupId>
      <artifactId>svg-salamander</artifactId>
      <version>1.1.5.5</version>
    </dependency>
  7. Use SVG in Swing forms with SVGPanel and SVGIcon

    master

    The library provides two Swing beans for easy integration:

    • com.kitfox.svg.app.beans.SVGPanel: A panel for displaying SVG content.
    • com.kitfox.svg.app.beans.SVGIcon: An icon implementation.

    Quick Setup for SVGPanel:

    1. Place the SVG file in your project's resources directory.
    2. Add an SVGPanel to your Swing form.
    3. Set the SvgResourcePath property to the path of your resource.
    4. Check ScaleToFit to ensure the graphic scales to the panel size.

    Note: Anti-aliasing is disabled by default for these components. Call setAntiAlias(true) to enable it.

  8. Pick elements at a specific point

    master

    To detect which SVG elements are located at a specific coordinate, use the SVGDiagram.pick(Point p, Vector results) method.

    It returns a Vector of Vector<SVGElements>. Each inner vector represents a path from the root of the diagram down to a specific RenderableElement that was hit by the point.

    SVGDiagram diagram = SVGCache.getSVGUniverse().getDiagram(uri); 
    Point pickPoint = new Point(20, 80); 
    Vector pickedElements = diagram.pick(pickPoint, null);
  9. Access SVG elements by ID

    master

    You can access specific parts of an SVG document using their id attribute via the SVGDiagram.getElement(String elementName) method. This allows you to read or write attributes of specific elements directly.

    // If SVG has <circle id="myCircle" ... />
    SVGElement circle = diagram.getElement("myCircle");
  10. Reference: SVGToImage Ant Task parameters

    master

    The following parameters are available for the <SVGToImage> Ant task:

    ParameterDescription
    destDirDirectory to write images to. Defaults to the SVG's directory.
    formatOutput format (e.g., png, jpg, gif). Defaults to png.
    backgroundColorBackground color (HTML name, #hex, or rgb()). Defaults to transparent.
    antiAliasIf set, enables anti-aliasing. Defaults to true.
    interpolationAlgorithm: nearest neighbor, bilinear, or bicubic. Defaults to bicubic.
    widthTarget width (> 0). Defaults to -1 (SVG width).
    heightTarget height (> 0). Defaults to -1 (SVG height).
    sizeToFitIf true, resizes the SVG area to fit the specified width/height.
    verboseIf true, prints diagnostic information. Defaults to false.
  11. Convert SVG to images using the Ant Task

    master

    The SVGToImage Ant task allows converting SVG files to images (PNG, JPG, GIF) via an Ant script. Include SVGSalamander.jar in your classpath.

    Example Task:

    <target name="testAntTask">
        <typedef name="SVGToImage" classname="com.kitfox.svg.app.ant.SVGToImageAntTask" classpath="path/to/svgSalamander.jar"/>
    
        <SVGToImage format="png" antiAlias="false" verbose="true">
            <fileset dir="examples">
                <include name="*.svg"/>
            </fileset>
        </SVGToImage>
    </target>
    <SVGToImage format="png" antiAlias="false" verbose="true">
        <fileset dir="examples">
            <include name="hinorei.svg"/>
        </fileset>
    </SVGToImage>