【问题标题】:Java: Take the image from Graphics and turn it into a temporary BufferedImageJava:从 Graphics 中获取图像并将其转换为临时的 BufferedImage
【发布时间】:2012-02-11 08:28:01
【问题描述】:

大家好,我正在制作一个 2D 游戏,我已经从 4 个预设图像生成了一个随机的草地背景。我的问题是,我的游戏使用此代码从游戏开始时创建的数组中绘制每个图像:

    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));
        }
    }
}

这很好用,但这就是问题所在。我正在使用以下方法重新绘制放入该数组的每个图像:

    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++;

        }
    }

}

这会导致 fps 下降(不是很多,但很明显)。无论如何,我可以将所有这些草图像绘制到一个 BufferedImage 中,以便它只是一个正在绘制的图像?或者有更有效的方法吗?

谢谢。

【问题讨论】:

  • 顺便说一句,创建一个Random 并重复使用它,而不是每次循环迭代都创建一个。

标签: java swing model bufferedimage graphics2d


【解决方案1】:

正如您所问的,没有办法从“图形中获取图像”,但是创建 BufferedImage 然后将图像绘制到其中并不是很难。如果有的话,AWT 的成像模型相当复杂,您必须构建一些辅助数据结构和其他东西,但这里有一个创建 32 位 RGBA 图像的模板:

private static final ComponentColorModel colormodel =
    new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
                            new int[] {8, 8, 8, 8}, true, false,
                            ComponentColorModel.TRANSLUCENT, DataBuffer.TYPE_BYTE);
public static BufferedImage makeimage(int w, int h) {
    WritableRaster buf = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, w, h, 4, null);
    return(new BufferedImage(colormodel, buf, false, null));
}

一旦您拥有makeimage() 创建的 BufferedImage,只需在其上调用 getGraphics() 并随心所欲地绘画。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 2011-05-14
    • 2017-07-27
    相关资源
    最近更新 更多