Hey guys I am making a 2D game and I have generating a random grassy background from 4 preset images. My problem is this, my game draws each image from an array which is created on game start using this code:
public static void createBackground() {
for(int x = 0; x < 640; x+= 32) {
for(int y = 0; y < 496; y+= 32) {
random = new Random();
int grassTex = random.nextInt(grassTextures.size());
grassPos.add(grassTextures.get(grassTex));
}
}
}
That works fine, but this is where the problem occurs. I am re-drawing every image that was put into that array using this:
public static void paintBackground(Graphics g) {
counter = 0;
for(int x = 0; x < 640; x+= 32) {
for(int y = 0; y < 496; y+= 32) {
random = new Random();
int grassTex = random.nextInt(grassTextures.size());
g.drawImage(grassPos.get(counter), x, y, null);
counter++;
}
}
}
This causes a drop in fps (It’s not a lot, but it is noticeable). Is there anyway that I can draw all those grass images into one BufferedImage so that it is only one image that is being drawn? Or is there a more efficient way of doing this?
Thanks.
There is no way to take “the image from Graphics”, as you ask, but it is not very hard to just create BufferedImage and then draw the image into it, instead. If anything, AWT’s imaging model is quite complex, and you’ll have to construct a couple of auxiliary data structures and stuff, but here’s a template which creates 32-bit RGBA images:
Once you have a BufferedImage as created by
makeimage(), just callgetGraphics()on it and paint to your heart’s content.