Java2D - How to rotate an image and save the result

I am making a game where some objects rotate to see what they are shooting at. There is a delay between shooting, and I want the subject to stand face to face until it shoots again. I know how to upload images, and I know how to rotate them using AffineTransform. But with this, I need to calculate the rotation every time the object is drawn.

So my question is: how can I rotate the image and save the result in a new image to be displayed?

+3
source share
3 answers

How can I rotate the image and save the result in a new image to be displayed?

BufferedImage. Graphics ( BufferedImage.getGraphics(). , ( , ).

+3

- :

BufferedImage source = new BufferedImage(50, 10, BufferedImage.TYPE_4BYTE_ABGR); 

BufferedImage target = new BufferedImage(50, 10, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D tg = target.createGraphics();

AffineTransform at = new AffineTransform();
at.rotate(2);

tg.drawImage(source, at, null);

P.S.: , . .

+1

Affline . . , , , - , , . , , , , . , . . x y , a > y a > .

private BufferedImage rotate(BufferedImage image, double _theta, int _thetaInDegrees) {

    AffineTransform xform = new AffineTransform();

    if (image.getWidth() > image.getHeight()) {
        xform.setToTranslation(0.5 * image.getWidth(), 0.5 * image.getWidth());
        xform.rotate(_theta);

        int diff = image.getWidth() - image.getHeight();

        switch (_thetaInDegrees) {
            case 90:
                xform.translate(-0.5 * image.getWidth(), -0.5 * image.getWidth() + diff);
                break;
            case 180:
                xform.translate(-0.5 * image.getWidth(), -0.5 * image.getWidth() + diff);
                break;
            default:
                xform.translate(-0.5 * image.getWidth(), -0.5 * image.getWidth());
                break;
        }
    } else if (image.getHeight() > image.getWidth()) {
        xform.setToTranslation(0.5 * image.getHeight(), 0.5 * image.getHeight());
        xform.rotate(_theta);

        int diff = image.getHeight() - image.getWidth();

        switch (_thetaInDegrees) {
            case 180:
                xform.translate(-0.5 * image.getHeight() + diff, -0.5 * image.getHeight());
                break;
            case 270:
                xform.translate(-0.5 * image.getHeight() + diff, -0.5 * image.getHeight());
                break;
            default:
                xform.translate(-0.5 * image.getHeight(), -0.5 * image.getHeight());
                break;
        }
    } else {
        xform.setToTranslation(0.5 * image.getWidth(), 0.5 * image.getHeight());
        xform.rotate(_theta);
        xform.translate(-0.5 * image.getHeight(), -0.5 * image.getWidth());
    }

    AffineTransformOp op = new AffineTransformOp(xform, AffineTransformOp.TYPE_BILINEAR);

    return op.filter(image, null);
}
+1
source

All Articles