2011-12-26 3 views
13

Potrzebuję móc obracać obrazy pojedynczo (w języku Java). Jedyne, co do tej pory znalazłem to g2d.drawImage (image, affinetransform, ImageObserver). Niestety, muszę narysować obrazek w określonym punkcie i nie ma metody z argumentem, że 1. obraca obraz oddzielnie i 2. pozwala mi ustawić x i y. każda pomoc jest doceniana.Java: Obracanie obrazów

Odpowiedz

25

Tak możesz to zrobić. Kod ten zakłada existance z buforowanego obrazu o nazwie „obraz” (jak mówi swoim komentarzu)

// 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

To działało, dzięki! – Jimmt

+2

Dlaczego tak skomplikowane? Transformacja zawiera zarówno obrót, jak i tłumaczenie, więc po prostu wykonaj 'g2d.drawImage (image, tx, ImageObserver)' z odpowiedzią 'tx'. –

+2

Dzięki, ale odcina część obrazu. – HyperNeutrino

8

AffineTransform przypadki mogą być łączone (sumowane). Dlatego możesz mieć transformację, która łączy "przesunięcie do punktu początkowego", "obrót" i "powrót do żądanej pozycji".

+4

+1 ["RotateApp'] (http://stackoverflow.com/a/3420651/230513) jest przykładem. – 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; 
} 

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

0

prosty sposób to zrobić bez użycia takiego skomplikowanego rachunku Draw:

//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);