2011-12-26 36 views
13

Tôi cần có khả năng xoay ảnh riêng lẻ (bằng java). Điều duy nhất tôi đã tìm thấy cho đến nay là g2d.drawImage (hình ảnh, affinetransform, ImageObserver). Thật không may, tôi cần phải vẽ hình ảnh tại một điểm cụ thể, và không có phương pháp với một đối số rằng 1.rotates hình ảnh một cách riêng biệt và 2. cho phép tôi để thiết lập x và y. bất kỳ trợ giúp nào được đánh giá làJava: Xoay ảnh

Trả lời

25

Đây là cách bạn có thể thực hiện. Mã này giả định sự tồn tại của một hình ảnh đệm gọi là 'image' (như nhận xét của bạn nói)

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

này làm việc, cảm ơn! – Jimmt

+2

Tại sao quá phức tạp? Biến đổi chứa cả phép xoay và dịch, do đó, chỉ cần thực hiện 'g2d.drawImage (hình ảnh, tx, ImageObserver)' với 'tx' từ câu trả lời. –

+2

Cảm ơn, nhưng nó cắt bỏ một số hình ảnh. – HyperNeutrino

8

AffineTransform trường hợp có thể được nối (vào với nhau). Vì vậy, bạn có thể có một biến đổi kết hợp 'chuyển sang nguồn gốc', 'xoay' và 'chuyển về vị trí mong muốn'.

+4

+1 ['RotateApp'] (http://stackoverflow.com/a/3420651/230513) là một ví dụ. – 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; 
} 

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

0

Một cách đơn giản để làm điều đó mà không cần dùng một tuyên bố rút thăm phức tạp như:

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