I want to draw SVG images, scaled, rotated, coloured and with an alpha layer onto a JPanel in my Java application. How can I achieve this? There may be multiple of these images overlapping.
I don't really know how to use SVG images in Java so please explain from the start, not only the rendering process :)
Thanks in advance!
You need to get the SVG image into a type that can be displayed by the JPanel -- I'm going to assume you already know how to use BufferedImage
to display e.g. a PNG, and that you don't need to edit the SVG, just display it.
The key here is that Java doesn't have native support for SVG. You have to use a library like batik to load and convert the image to a displayable format.
I stole this answer from http://bbgen.net/blog/2011/06/java-svg-to-bufferedimage/
Write a simple Transcoder
class BufferedImageTranscoder extends ImageTranscoder
{
@Override
public BufferedImage createImage(int w, int h)
{
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
return bi;
}
@Override
public void writeImage(BufferedImage img, TranscoderOutput output)
{
this.img = img;
}
public BufferedImage getBufferedImage()
{
return img;
}
private BufferedImage img = null;
}
Using the Transcoder
public static BufferedImage loadImage(File svgFile, float width, float height)
{
BufferedImageTranscoder imageTranscoder = new BufferedImageTranscoder();
imageTranscoder.addTranscodingHint(PNGTranscoder.KEY_WIDTH, width);
imageTranscoder.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, height);
TranscoderInput input = new TranscoderInput(svgFile);
imageTranscoder.transcode(input, null);
return imageTranscoder.getBufferedImage();
}
Then, just display the rendered BufferedImage
on your JPanel as if it were a PNG or whatever.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With