jor
jor

Reputation: 843

Java 2D : Creating Shape Fixtures

I'm wondering if there is a way to create a shape fixture in Java 2D.

More specifically, I'm trying to be able to draw a predefined shape at different locations with different colors.

I know you can use the fill(shape) methods to draw shapes. However, this seems to require creating a new shape at the coordinate that I want to draw it.

Is there any way to reuse the same shape each time? Or do I have to create a new shape for each location.

Upvotes: 0

Views: 103

Answers (1)

Quijx
Quijx

Reputation: 366

You can do this by translating the transformation matrix of the graphics object.
Let's say you have a Shape called shape whose coordinates are relative to the center of the Shape. You also have an instance of Graphics2D called g2.
Now you code could look something like this:

// Set the color of the Shape.
g2.setColor(Color.BLACK);
// Backup the transformation matrix so we can restore it later.
AffineTransform backupTransform = new AffineTransform(g2.getTransform());
// Translate everything that is drawn afterwards by the given coordinates.
// (This will be the new position of the center of the Shape)
g2.translate(53, 27);
// Draw the Shape.
g2.draw(shape);
// Restore the old transform, so that things drawn after this line
// are not affected by the translation.
g2.setTransform(backupTransform);

Upvotes: 4

Related Questions