Question

I have a game which runs in an applet. In there, there's a missile, which should point up, down, left or right. One way doing it would be creating 4 images (one for each direction), but that would be too complicated.

Does anyone know a way I rotate the image, once it's loaded into the program?

Was it helpful?

Solution

You can follow this example using applet in java awt to rotate an image .

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.net.URL;

public class RotateImage extends Applet {

private Image image;

AffineTransform identity = new AffineTransform();

 private URL getURL(String filename) {
 URL url = null;
 try {
 url = this.getClass().getResource(filename);
 }
catch(Exception e){}
return url;
}

public void init() {
image = getImage(getCodeBase(), "image.jpg");
}

public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
AffineTransform trans = new AffineTransform();
trans.setTransform(identity);
trans.rotate( Math.toRadians(45) );
g2d.drawImage(image, trans, this);
}
}

The most complicated part of the code is the AffineTransform object. According to Sun's AffineTransform API, "The AffineTransform class represents a 2D affine transform that performs a linear mapping from 2D coordinates to other 2D coordinates that preserves the "straightness" and "parallelness" of lines." If you experiment a little with this class (or just continue reading the API), you'll see that it can be used not just to rotate, but also to scale, flip, and shear an image as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top