6
\$\begingroup\$

I get great FPS with this as is, but I'm a performance freak and I don't know AffineTransform or the Java graphics libraries very well. I'm sure there is something I could be doing differently to make this faster, but I can't think of anything, other than it looks like the scale transformation gives me a big performance hit, probably because of the algorithm Graphics2D uses to draw the scaled pixels. I'd be fine with it using a different algorithm that doesn't blend colors if that would make things run faster, but I don't know where to even begin to try to do that.

I dumbed down my code to give you a good idea of what's going on (I hope). I'm only concerned about the render method.

public BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
public Graphics2D graphics = image.createGraphics();

public void render(BufferedImage img, Vector2 center, Vector2 offset, double rotation, Vector2 scale) {
    graphics.setTransform((AffineTransform) defaultTransform.clone());
    graphics.rotate(rotation, center.x, center.y);
    graphics.scale(scale.x, scale.y);
    graphics.translate(center.x / scale.x + offset.x, center.y / scale.y + offset.y);
    graphics.drawImage(img, null, 0, 0);
}

public class Vector2 {
    double x = 0.0, y = 0.0;
}
\$\endgroup\$
4
\$\begingroup\$

Sometimes, the correct answer really is "Nope; it's all good." It makes for a boring answer, but there it is. It doesn't look like you can make this much faster, based on what you've provided.

One thing you might consider is checking the variables to see if the image manipulations are actually needed before calling the respective methods. So, for example, something like...

graphics.setTransform((AffineTransform) defaultTransform.clone());
if(rotation != 0.0) {
    graphics.rotate(rotation, center.x, center.y);
}
if(scale.x != img.getWidth() || scale.y != img.getHeight()) {
    graphics.scale(scale.x, scale.y);
}
//...

This might give you a bit of performance where you don't need to bother going down into the rotate() and scale() methods.

Also, is there any way you can get rid of that (AffineTransform) cast? Probably not, but that would speed you up ever so slightly.

\$\endgroup\$

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.