Reputation: 103
I am making a game. It is a 2D game, and the map is drawn by a double loop like this:
for(int i = 0; i < mapArray.length; i++){
for(int j = 0; j < mapArray[1].length; j++){
//if statement for if its on the screen
g.drawImage(tiles.get(mapArray[i][j]).getImage(), j * textureSize, i * textureSize, null);
}
}
They are 32x32 images, and I was wondering stitching them all together to create one large image at the beginning would be more efficient in drawing. The resulting image would only be around 1500x1500.
I was thinking of making it stitched into one image (Especially since I am planning on making the images smaller which would make the loop need ever more time.) so that it didn't have to run through the double for loop every time it renders (shooting for 60 FPS). But I don't know how to do this, and would it actually improve the performance if I did?
Also, I could just stitch them into rows, and only render the rows that are on the screen(to remove the large image problem) So it would still be much less intensive than that crazy loop I've got right now.
Edit: And one last thing, if you can provide an example of how to do this without extra libraries that would be optimal.
I currently have this code for stitching:
Edit: now works. Leaving this here for future readers:
public void stitchImages(){
BufferedImage temp = new BufferedImage( <Width> , <height> , BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) temp.getGraphics();
for (int b = 0; b < mapArray.length; b++) {
for (int a = 0; a < mapArray[b].length; a++) {
g.drawImage(tiles.get(mapArray[b][a]).getImage(),
(int) mapX + a * textureSize, (int) mapY + b
* textureSize, null);
}
}
mapImage = temp;
}
Upvotes: 3
Views: 1332
Reputation: 35031
Create a new Image to encapsulate all of your images. Draw your images when you load up, then just draw that in paintComponent()
BufferedImage im = new BufferedImage(1500,1500,BufferedImage.TYPE_INT_RGB);
private void init() {
Graphics g = im.getGraphics();
for(int i = 0; i < mapArray.length; i++){
for(int j = 0; j < mapArray[1].length; j++){
//if statement for if its on the screen
g.drawImage(tiles.get(mapArray[i][j]).getImage(), j * textureSize, i * textureSize, null);
}
}
}
public void paintCompoent(Graphics g) {
super.paintComponent(g);
g.drawImage(im,0,0,null);
}
EDIT:
As for your idea about just painting the lines that are on the screen, you can do that by creating an Image
the size of the window and just drawing to that. But in general, it's not a big problem to paint a big Image (as long as the Image fits in memory and you don't get an OutOfMemoryException) as your GPU's capabilities smoke your CPU's
Upvotes: 1