Reputation: 2004
I am making a Java game, and the game lags a lot when I paint out the graphics.
The way I am currently painting out the graphics is to make a BufferedImage
, get the Graphics2D
from it, then do a whole bunch of:
g2d.drawImage(loadedImages.getImage(),x,y,null);
After I print all of the images to the BufferedImage
, I paint the BufferedImage
to the screen.
There are a lot of images I paint to the BufferedImage
. Is there a better way to do this that would speed up the painting time?
I do not know much about graphics and graphic cards. Should I use a graphics card? Should I paint directly to the screen? Should I use something entirely different than drawImage()
?
Upvotes: 3
Views: 3382
Reputation: 2647
I've found it useful to extend java.awt.Canvas and use
BufferStrategy bs;
void init() {
createBufferStrategy(2);// or 3 for triple-buffering
bs = getBufferStrategy();
}
and then the actual draw()
method looks like
void draw() {
Graphics g = bs.getDrawGraphics();
g.drawImage(image, x, y, w, h, null);
// Draw more things here...
// You can also make calls like `myObject.draw(g)` and whatever
// you draw onto `g` within those calls will show up.
bs.show();
g.dispose();
}
This is what I use for drawing a lot of things. And then within each myObject.draw(g)
call, there are sometimes multiple other similar calls all chained up. Most often my main draw()
method has one or two for
loops in it that just say for(Entity e: entities) e.draw(g);
or something similar. Then the whole drawing chain is kicked off from there.
Upvotes: 1
Reputation: 1138
The performance should be good if you're drawing a reasonable amount of images.
Make sure you're not creating new BufferedImage
s every time you draw to the screen. For example, you might have a Resources
singleton in which you manage all of your images so that you only load and unload each image once.
If you really want more performance, you'll want to use OpenGL. See LWJGL, libgdx, or JOGL. You may also want to consider 2D graphics libraries like Slick.
Upvotes: 4