Reputation: 319
I am creating a game of space invaders and i would like for all of the images to be in ratio to the screen resolution. This means that it can be used on all screen sizes and all the images will shrink or get bigger so that they fit onto the screen. The game is fullscreen. What is the easiest technique to do this? Also is this the best way to set the size of everything?
Upvotes: 4
Views: 36488
Reputation: 11
Image getScaledImage(Image Img, int wt, int ht) {
BufferedImage resizedImg = new BufferedImage(wt, ht, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(Img, 0, 0, wt, ht, null);
g2.dispose();
return resizedImg;
}
Upvotes: 1
Reputation: 36423
Have you had a look at Image#getScaledInstance() though it has its downfalls(The Perils of Image.getScaledInstance()) in short the problem is:
Image.getScaledInstance() does not return a finished, scaled image. It leaves much of the scaling work for a later time when the image pixels are used.
due to these downfalls you might want a different way to resize your images, you could try something like this:
import javax.swing.ImageIcon;
import java.awt.image.BufferedImage;
import java.awt.Image;
import java.awt.Color;
import java.awt.Graphics2D;
import java.io.File;
import javax.imageio.ImageIO;
import java.awt.RenderingHints;
public class ImgUtils {
public BufferedImage scaleImage(int WIDTH, int HEIGHT, String filename) {
BufferedImage bi = null;
try {
ImageIcon ii = new ImageIcon(filename);//path to image
bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(ii.getImage(), 0, 0, WIDTH, HEIGHT, null);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return bi;
}
}
you'd use it like:
BufferedImage img=new ImgUtils().scaleImage(50,50,"c:/test.jpg");
//now you have a scaled image in img
References:
Upvotes: 5
Reputation: 111
Suppose g is your instance of the Graphics2D object, and theImage is the Image you want to draw, and xFactor and yFactor are the scaling factors for x and y, try:
AffineTransformation scaleTransformation = AffineTransformation.getScaleInstance(xFactor, yFactor);
g.draw(theImage, scaleTransformation, null);
Upvotes: 1