如何使用compatibleImage在java2D中更快地绘制图像?

时间:2015-03-15 22:46:26

标签: bufferedimage java-2d drawimage

我正在用Java2D编写一个游戏,它在我的计算机和我测试过的另一台计算机上运行顺畅。但是在另一台计算机上,具有不错的规格和相同的Java设置,它非常慢。我很确定我将其缩小到g.drawImage()命令。在做了一些研究之后,我发现有人制作了一个方法来编译他发现为提高速度而工作的一些东西,方法是:

public BufferedImage toCompatibleImage(BufferedImage image) {
    // obtain the current system graphical settings
    GraphicsConfiguration gfx_config = GraphicsEnvironment
            .getLocalGraphicsEnvironment().getDefaultScreenDevice()
            .getDefaultConfiguration();



     //if image is already compatible and optimized for current system
     //settings, simply return it

    if (image.getColorModel().equals(gfx_config.getColorModel())) {

        return image;
    }

    // image is not optimized, so create a new image that is
    BufferedImage new_image = gfx_config.createCompatibleImage(
            image.getWidth(), image.getHeight(), Transparency.TRANSLUCENT);

    // get the graphics context of the new image to draw the old image on
    Graphics2D g2d = (Graphics2D) new_image.getGraphics();

    // actually draw the image and dispose of context no longer needed
    g2d.drawImage(image, 0, 0, null);
    g2d.dispose();

    // return the new optimized image
    // System.out.println(image.getColorModel());
    return new_image;
}

我很困惑你如何使用这种方法。我弄完了: 1)使用Image.IO从png创建图像时调用它。

BufferedImage img = toCompatibleImage(theLoadedImage);

然后在paintComponent(Graphics g)方法中简单地调用

 Graphics2D g2 = (Graphics2D) g;
 g.drawImage(img, x, y, null); 

2)在每次重画中调用它如下:

 Graphics2D g2 = (Graphics2D) g;
 g.drawImage(toCompatibleImage(theLoadedImage), x, y, null);

除了FPS中的名义变化之外,其他两个似乎都做不了什么,第一种方法稍快一些。我不知道我是否使用这个权利,所以帮助和基本解释会非常有用。

1 个答案:

答案 0 :(得分:1)

您应该使用第一种方法,只需转换一次即可。

兼容图像在内部以与视频卡相同的格式存储像素,因此每次绘制时都不需要转换它们。