Search code examples
javagraphics2d

Write a Graphics2D object into another Graphics2D object


Is there a way to render a Graphics2D object into another Graphics2D object. Not by turning one into an Image and drawing that, but as the graphics primitives?

As an example, let's say I want to draw the same start 5 times. So I create a Graphics2D object, render the star to it. I then render that star Graphics2D object 5 times in my main Graphics2D object, at 5 distinct locations.

By retaining all the line draw primitives, then when I create a final SVG file from the Graphics2D object, it can zoom in 1,000 times and it's still a clean render.

Is there a way to do this?


Solution

  • A Graphics2D is a sink for rendering commands. It never acts as a source, as you can easily deduce from the absence of any methods that would remotely fit this purpose (namely any methods that support reading the actual contents of the graphics).

    This is also a clean approach from a design standpoint, Graphics is intended to allow rendering to not only pixel rasters, but any kind of graphical device.

    Although, since Graphics is just an abstract class, you can create implementations that allow you to read back the contents, but not through the Graphics2D API. Its always a specifically added capability through an unrelated API (e.g. BufferedImage).

    If your goal is to create an SVG, there are vector based primitives you could use; theres a whole bunch of subclasses of java.awt.Shape you can use to define the geometry. Shapes can be rendered in a Graphics2D or you can "traverse" a Shape using getPathIterator() and perform whatever operation you need.

    For the simple purpose of rendering a predefined geometry multiply times, Shapes are the vector equivalent of a pixel image (In case you are wondering, you will need to make use of translate/transform to re-position a Shape when rendering, there are no calls that take coordinates for shapes).

    For creating more complex shapes out of basic shapes, you can make use of the API java.awt.geom.Path2D which for example has a concrete implementation called GeneralPath that allows to combine shapes.

    EDIT: So to put it simple, Graphics2D is not the right tool for your task, Shape/GeneralPath is.