1
\$\begingroup\$

An example image

As you can see above, I have an image of a game I've been working on using Java. Using AWT I added the following:

public static void drawImageRotated(
        Graphics2D g2d, BufferedImage img, double x, double y, int scale, double angle) {

    BufferedImage image = new BufferedImage(
                                     (int)(img.getWidth() * 1.5D),
                                     (int)(img.getHeight() * 1.5D),
                                     2);
    Graphics2D g = (Graphics2D)image.getGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.rotate(Math.toRadians(angle), image.getWidth() / 2, image.getHeight() / 2);
    g.drawImage(img,
                image.getWidth()  / 2 - img.getWidth() / 2,
                image.getHeight() / 2 - image.getHeight() / 2,
                null);
    g2d.drawImage(image,
                 (int)x-(image.getWidth()*scale/2),
                 (int)y-(image.getHeight()*scale/2),
                 image.getWidth()*scale,
                 image.getHeight()*scale,
                 null);
    g.dispose();      
}

This is the code which draws the ships onto the screen. As you can see there is a blue and a cyan ship on the screen, the blue ship's rotation being 0 and the cyan having a rotation of just over 270 degrees. The cyan ship is distorted and that's what I want to get rid of. Is there an anti-aliasing for small images like that one (16x16)?

\$\endgroup\$
  • 5
    \$\begingroup\$ This is a 16x16 image rotated at a non-right angle; what output are you expecting? \$\endgroup\$ – mmyers Feb 1 '13 at 16:46
  • \$\begingroup\$ After reformatting the code, it appears there is an error in the g.drawImage call. Shouldn't the y position be image.getHeight()/2 - img.getHeight()/2? \$\endgroup\$ – mmyers Feb 1 '13 at 17:00
  • \$\begingroup\$ So I'm assuming I need to make the image slightly larger. \$\endgroup\$ – Shaun Wild Feb 1 '13 at 17:19
2
\$\begingroup\$

That code seems more complicated than necessary, what you need is to just draw your image with the right transformation matrix.

I don't speak Java so there may be mistakes in this, but it should look something like:

AffineTransform transform = new AffineTransform();
transform.rotate(angle,img.getWidth()/2,img.getHeight()/2);
transform.scale(scale,scale);
transform.translate(x,y);
g2d.drawImage(img,transform,null);

The first 4 lines build a translation matrix, you don't need to worry much about how that works, except that the construction order matters.

\$\endgroup\$
  • \$\begingroup\$ For the record, this should also produce a different visual result. \$\endgroup\$ – aaaaaaaaaaaa Feb 2 '13 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.