Sign in to follow this  
MatejaS

Java Graphics2D not rotating right

Recommended Posts

Hello,

I tried to make a program where two rectangles are rotating around their centers.

But the second of them is orbiting around the first one.

Code:

private void drawRect(int x, int y, int width, int height, double angle,
			Graphics2D g2) {
		AffineTransform old = g2.getTransform();
		AffineTransform af = new AffineTransform();
		af.rotate(Math.toRadians(angle), (double) width / 2.0,
				(double) height / 2.0);
		
		g2.transform(af);

		g2.fillRect(x, y, width, height);

		g2.transform(old);
	}

and then:

g2.setColor(Color.BLUE);
drawRect(0,0,100,100,angle,g2);

g2.setColor(Color.RED);
drawRect(200,200,50,100,angle2,g2);
angle+=0.3;
angle2++;

I tried using g2.rotate first,but it gave me the same problem,so I tried using AffineTransform.Of course,nothing changed...

Screenshot is attached.

Help!!!

Thanks,

MatejaS

Share this post


Link to post
Share on other sites

This looks like homework.  biggrin.png

 

It looks like you're using the transform() method which takes the given transform and adds it to the current transform, but you want the setTransform() method which overwrites the current transform with the new transform.  

 

Javadocs are your friend.  

http://docs.oracle.com/javase/8/docs/api/java/awt/Graphics2D.html#transform-java.awt.geom.AffineTransform-

Share this post


Link to post
Share on other sites

Thanks @Glass_Knife but it didn't help...

It seems that even if I remove all code for drawing the blue rect,the red rect still orbites.Same thing if I first draw red,and then blue rect... Weird...

And it's not homework :)

Share this post


Link to post
Share on other sites

and you changed it all to setTransform() and it still didn't work?  Hmm.  It is time to create a condensed example and post to whole thing so someone can run it or at least see everything.

 

I do remember that the AffineTransform does a column major multiply, so the combinations go in reverse order from what you might expect, but I've done this before and it does work just like it should.

Share this post


Link to post
Share on other sites

Maybe I'm wrong here, but the anchor point you are using for your rotation is just width/2, height/2, you have to adjust for the x and y coordinates of the rectangle. If you modify your anchor point to:

af.rotate(Math.toRadians(angle), (double) (x + width / 2.0),
                (double) (y + height / 2.0));

Let us know...

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this