2011-12-26 11 views
13

Devo essere in grado di ruotare le immagini individualmente (in java). L'unica cosa che ho trovato finora è g2d.drawImage (image, affinetransform, ImageObserver). Sfortunatamente, ho bisogno di disegnare l'immagine in un punto specifico, e non c'è alcun metodo con un argomento che 1.rotini l'immagine separatamente e 2. mi permetta di impostare xey. ogni aiuto è graditoJava: Rotating Images

risposta

25

Ecco come si può fare. Questo codice presuppone l'esistenza di un'immagine tamponato chiamato 'immagine' (come dice il tuo commento)

// The required drawing location 
int drawLocationX = 300; 
int drawLocationY = 300; 

// Rotation information 

double rotationRequired = Math.toRadians (45); 
double locationX = image.getWidth()/2; 
double locationY = image.getHeight()/2; 
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY); 
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR); 

// Drawing the rotated image at the required drawing locations 
g2d.drawImage(op.filter(image, null), drawLocationX, drawLocationY, null); 
+0

questo ha funzionato, grazie! – Jimmt

+2

Perché così complesso? La trasformazione contiene sia la rotazione che la traduzione, quindi basta 'g2d.drawImage (immagine, tx, ImageObserver)' con il 'tx' dalla risposta. –

+2

Grazie, ma taglia alcune delle immagini. – HyperNeutrino

8

AffineTransform istanze possono essere concatenate (sommati). Quindi puoi avere una trasformazione che combina lo "spostamento all'origine", la "rotazione" e lo "spostamento indietro nella posizione desiderata".

+4

+1 ['RotateApp'] (http://stackoverflow.com/a/3420651/230513) è un esempio. – trashgod

0
public static BufferedImage rotateCw(BufferedImage img) 
{ 
    int   width = img.getWidth(); 
    int   height = img.getHeight(); 
    BufferedImage newImage = new BufferedImage(height, width, img.getType()); 

    for(int i=0 ; i < width ; i++) 
     for(int j=0 ; j < height ; j++) 
      newImage.setRGB(height-1-j, i, img.getRGB(i,j)); 

    return newImage; 
} 

da https://coderanch.com/t/485958/java/Rotating-buffered-image

0

Un modo semplice per farlo senza l'uso di una tale affermazione pareggio complicato:

//Make a backup so that we can reset our graphics object after using it. 
    AffineTransform backup = g2d.getTransform(); 
    //rx is the x coordinate for rotation, ry is the y coordinate for rotation, and angle 
    //is the angle to rotate the image. If you want to rotate around the center of an image, 
    //use the image's center x and y coordinates for rx and ry. 
    AffineTransform a = AffineTransform.getRotateInstance(angle, rx, ry); 
    //Set our Graphics2D object to the transform 
    g2d.setTransform(a); 
    //Draw our image like normal 
    g2d.drawImage(image, x, y, null); 
    //Reset our graphics object so we can draw with it again. 
    g.setTransform(backup);