So Im drawing a BufferedImage 'bird' but I want to rotate it according to the angle that it is falling. I have a bird object which contains the BufferedImage and a render() method which draw it rotated.
public void render(Graphics2D g, ImageObserver io) {
double theta = Math.tan((height - pastHeight) / .875);
System.out.println(theta);
Graphics2D g2 = (Graphics2D) bird.getGraphics();
g2.drawImage(bird, 100, (int) height, null);
g2.rotate(theta);
g2.drawImage(bird, 100, (int) height, io);
}
I call this as such
bird.render(g2, ???);
in my paintcomponent method in my jcomponent.
only problem is I dont know what to use as my ImageObserver... I've tried passing in my JFrame and my JComponent but the image no longer appears when I do that... what would I pass in for the image to appear in my window and/or how else would I achieve this rotation?
Assuming that you are doing this in something that extends
JComponent
, you should useAs
JComponent
implementsImageObserver
The problem with the image disappearing isn't an issue with the
ImageObserver
but the point around which the rotation is occurring, which I believe is the top/left corner of theGraphics
context.Try using
Graphics2D#rotate(double, int, int)
which will allow you to specify the origin points of the rotation (pivot point).Don't forget to reset your translations, as they will effect everything that is painted after your supply them and may be re-used in subsequent paint cycles.
Updated with simple example
This is a basic example that demonstrates the different uses of
rotate
.First, I simply used
Graphics#rotate(double)
Then I replaced
g2d.rotate(Math.toRadians(angel));
withg2d.rotate(Math.toRadians(angel), getWidth() / 2, getHeight() / 2);
, which used the center position of the component (or theGraphics
context) as the anchor point around which the rotation would occur...Now, because you only want to rotate your image, you're going to need to calculate the anchor point around the current position of the image's center position (assuming you want it to rotate around the middle)