Java:旋转图像

时间:2011-12-26 22:31:38

标签: java image swing rotation graphics2d

我需要能够单独旋转图像(在java中)。到目前为止我唯一发现的是g2d.drawImage(image,affinetransform,ImageObserver)。不幸的是,我需要在特定的点绘制图像,并且没有一个方法可以分别对图像进行旋转,并且2.允许我设置x和y。任何帮助表示赞赏

5 个答案:

答案 0 :(得分:29)

这就是你如何做到的。此代码假定存在一个名为“image”的缓冲图像(如评论所示)

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

答案 1 :(得分:8)

AffineTransform个实例可以连接(加在一起)。因此,您可以将变换结合起来“转换为原点”,“旋转”和“转换回所需位置”。

答案 2 :(得分:1)

一种简单的方法,可以在不使用如此复杂的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.
    g2d.setTransform(backup);

答案 3 :(得分: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;
}

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

答案 4 :(得分:0)

对不起,但是对于图形初学者来说,所有答案都很难理解...

经过一番摆弄之后,这对我有用,并且很容易推理。

@Override
public void draw(Graphics2D g) {
    AffineTransform tr = new AffineTransform();
    // X and Y are the coordinates of the image
    tr.translate((int)getX(), (int)getY());
    tr.rotate(
            Math.toRadians(this.rotationAngle),
            img.getWidth() / 2,
            img.getHeight() / 2
    );

    // img is a BufferedImage instance
    g.drawImage(img, tr, null);
}

我想如果要旋转矩形图像,此方法将不起作用,并且会剪切图像,但是我想您应该创建方形png图像并将其旋转。