I need to render a large amount of images for my game and they need to be scaled to any aspect ration to fit the screen and I can't find a solution anywhere.
It already renders the image just not in the correct aspect ratio.
Rendering code:
class _canvas extends JComponent {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (renderable_object part : objs) {
if (part.type == 5) {
g.drawImage(part.get_Image(), part.i, part.j, 23,23);
}
}
}
}
Renderable object:
class renderable_object {
int i = 0;
int j = 0;
int k = 0;
int l = 0;
int type = 0;
String file = "";
Image get_Image() {
return(Toolkit.getDefaultToolkit().getImage(file));
}
}
The code you show does not scale the image at all. There are at least two ways you can go from here.
You already found the correct method (looking at the title of the question) to use. With that method you can define the source and destination coordinates and rendering will happen accordingly. It seems it is up to you to ensure the coordinates you demand have the correct aspect ratio.
Another possibility would be to cast Graphics into a Graphics2D, then use https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/java/awt/Graphics2D.html#drawImage(java.awt.Image,java.awt.geom.AffineTransform,java.awt.image.ImageObserver) to actually render the image. The scaling and exact positioning of the image can now be done via AffineTransform, which you could obtain by
getScaleInstance(double sx, double sy).concatenate(getTranslateInstance(double tx, double ty))
so it might be easier to setup. This way it is also very easy to apply rotation, shearing or other stuff.