Aage Torleif
Aage Torleif

Reputation: 2013

How to rotate two shapes around two different points with Graphics2D?

I'm trying to make a quadcopter like shape, so I have to rotate different shapes around different points.

The following snippet works for the first rectangle and not the second.

public void render(Graphics2D g) {
    // cx and cy is the center of the shape these spin near

    // add prop rotation
    at = g.getTransform();
    at.rotate(Math.toRadians(prop_rotation), cx, cy-42);
    g.setTransform(at);

    // Rect 1 spins correctly!
    g.fillRect(cx-14, cy-45, 28, 6);

    at = g.getTransform();
    at.rotate(Math.toRadians(prop_rotation), cx, cy+38);
    g.setTransform(at);
    // Rect 2 spins around rect 1
    g.fillRect(cx-14, cy+35, 28, 6);
}

Picture

So how do I do this with multiple centers?

Upvotes: 1

Views: 64

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

Transformations are accumlitive.

Start by grabbing a copy of the Graphics context and modifying it in isolation...

Graphics2D copy = (Graphics2D)g.create();
at = copy.getTransform();
at.rotate(Math.toRadians(prop_rotation), cx, cy-42);
copy.setTransform(at);

// Rect 1 spins correctly!
copy.fillRect(cx-14, cy-45, 28, 6);
copy.dispose();

Graphics2D copy = (Graphics2D)g.create();
at = copy.getTransform();
at.rotate(Math.toRadians(prop_rotation), cx, cy+38);
copy.setTransform(at);
// Rect 2 spins around rect 1
copy.fillRect(cx-14, cy+35, 28, 6);
copy.dispose();

This basically makes a copy of the Graphics properties, but still allows you to paint to the same "surface". Changing the copies properties won't affect the originals.

An alternative might be to transform the shape itself...

private Rectangle housing1;
//...
housing1 = new Rectangle(28, 6);

//...

AffineTransform at = new AffineTransform();
at.translate(cx - 14, cy - 45);
at.rotate(Math.toRadians(prop_rotation), cx, cy - 42);
Shape s1 = at.createTransformedShape(housing1);
g.fill(housing1);

This way, you don't mess with the Graphics context (which is always nice) and you gain a handy little piece which could be re-used, example, for the other side...

at = new AffineTransform();
at.translate(cx-14, cy+35);
at.rotate(Math.toRadians(prop_rotation), cx, cy + 38);
Shape s2 = at.createTransformedShape(housing1);
g.fill(housing2);

Upvotes: 1

Related Questions