简体   繁体   中英

How to Rotate with AffineTransform and keep the orignal coordinates system?

I'am a command pattern to rotate and translate shapes on Java Swing The translation and the rotation work well separatly, but when I do a 60 deg. rotation and then the translation, the translation follow the new rotated coordinate. Which means if I drag the mouse, the shape moves with a 60 deg gap from the mouse mouvement vector is there any easy solution ? please help, I'am hitting a wall here

My execute method for the rotation

public void execute() {  
    System.out.println("command: rotate " + thetaDegrees );       
    Iterator iter = objects.iterator();  
    Shape shape;  
    while(iter.hasNext()){  
        shape = (Shape)iter.next();           
        mt.addMememto(shape);             
        AffineTransform t =  shape.getAffineTransform();      
        t.rotate(Math.toRadians(thetaDegrees), shape.getCenter().x, shape.getCenter().y);  
        shape.setAffineTransform(t);              
    }  
}  

My execute method for the translation

public void execute() {  
    Iterator iter = objects.iterator();  
    Shape shape;  
    while(iter.hasNext()){  
        shape = (Shape)iter.next();  
        mt.addMememto(shape);  
        AffineTransform t = shape.getAffineTransform();  
        System.out.println("Translation x :"+x + ", Translation y :"+y);  
        t.translate(x,y);  
        shape.setAffineTransform(t);  
    }  
} 

Any help can be really appreciated

To accomplish an "in-place" rotation (where the object rotates about its own axis), you must:

  1. translate the object to the origin
  2. apply the rotation
  3. translate back to the original position
  4. apply the desired translation

Note that steps 3 and 4 could be applied at once.

If rotation is attempted at position other than the origin, a "revolving" effect is achieved - one where the object appears to be revolving about the origin.

You're using a special rotate function that will take account of the offset of the shape in order to properly rotate around its center. However you need to do something similar for the translate function in order to take account of the orientation of the shape.

Try this instead for your translate function:

public void execute() {  
    Iterator iter = objects.iterator();  
    Shape shape;  
    while(iter.hasNext()){  
        shape = (Shape)iter.next();  
        mt.addMememto(shape);  
        AffineTransform t = new AffineTransform();
        System.out.println("Translation x :"+x + ", Translation y :"+y);
        t.translate(x,y);
        t.concatenate(shape.getAffineTransform());
        shape.setAffineTransform(t);  
    }  
}

This executes the translation in the original coordinate system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM