Domanda

Vorrei far ruotare un rettangolo attorno al suo punto centrale e dovrebbe rimanere nel posto che si suppone essere disegnato e ruotare in quello spazio

Questo è il mio codice:

AffineTransform transform = new AffineTransform();

    transform.rotate(Math.toRadians(45),rectangle.width/2, rectangle.height/2);
    Shape transformed = transform.createTransformedShape(rectangle);
    g2.fill(transformed)

il rettangolo è ruotato, ma è disegnato in una parte diversa dello schermo, come posso correggere questo?

È stato utile?

Soluzione

I haven't tried this, but it seems you aren't getting the correct middle of the rectangle. Try:

AffineTransform transform = new AffineTransform();
transform.rotate(Math.toRadians(45), rectangle.getX() + rectangle.width/2, rectangle.getY() + rectangle.height/2);
g2.fill(transformed);

The difference is now you're adding the width to the starting X point and adding the height to the starting Y point, hence the middle of the rectangle.

Hope this helps.

Altri suggerimenti

AffineTransform transform = new AffineTransform();
transform.rotate(theta, rect.getX() + rect.width/2, rect.getY() + rect.height/2);
AffineTransform old = g2.getTransform();
g2.transform(transform);

// draw your rectangle here...

g2.setTransfrom(old);

If you do it like that, its possible to draw a more advanced rectangle. For example with a gradient fill, or text inside the rectangle. Everything will rotate with it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top