0
\$\begingroup\$

I am trying to make my second java game (2D) but i have run in a problem: The game will be in fullscreen, but how can i make it so it is scaled properly for each screen? While researching i found out that (almost) everyone is saying the same thing: render it on a Buffered image first and then render the image on the screen resolution, which i understund how to do ( BufferedImage i = new BufferedImage(width, height, 1); BufferStrategy bs = this.getBufferStrategy();

Graphics2D g2 = i.createGraphics();
if(bs == null){
    this.createBufferStrategy(3);
    return;
}

Graphics g = bs.getDrawGraphics();
//g2.draw....

g.dispose();
bs.show();

) but wont that make everything look squeezed or streched? P.s. if you know any way of making it scale only by keeping the starting resolution (leaving black on both sides) i would accept it

P.s.Sorry for my english.Hope i explained it good enough (if not ask me to clarify)

\$\endgroup\$
1
\$\begingroup\$

Just render the image on your JFrame/JPanel using g.drawImage(img, x, y, width, height, obs) with this trick:

JPanel panel = ...; // Your target panel
Graphics g = ...; // The graphics object of this panel (argument of paintComponent)

float scale = Math.min((float) panel.getWidth() / i.getWidth(), (float) panel.getHeight() / i.getHeight());

int displayWidth = (int) (i.getWidth() * scale);
int displayHeight = (int) (i.getHeight() * scale);

g.drawImage(i, panel.getWidth()/2 - displayWidth/2, panel.getHeight()/2 - displayHeight/2, displayWidth, displayHeight, null);

This way you keep the aspect ratio of the BufferedImage but scale it to take the maximum place of the panel.

Also, if the BufferedImage is smaller than the panel, then you might notice some artifacts. The easiest way to fix them is to set the rendering hint INTERPOLATION to something better, like BILINEAR:

g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
\$\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.