在Java中加载和缓存图像的最佳方法是什么? [英] What is the best way to load and cache images in Java?

查看:161
本文介绍了在Java中加载和缓存图像的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个超过一千个16乘16像素平铺图像的大集合,我将用Java制作一个游戏。

I have a large collection of over one thousand 16 by 16 pixel tile images that I'll need for a game I'm making in Java.

什么会存储瓷砖的最佳方式是不会耗尽JVM的可用内存?

What would be the best way to store the tiles without exhausting the available memory of the JVM?

我认为产生1000+ BufferedImages可能不是明智的......

I'm thinking that spawning 1000+ BufferedImages might not be wise...

保持图像准备就绪的主要目的是加载地图,这些地图将根据地图文件动态生成。

The main purpose for keeping the images at the ready is for loading maps, which will be dynamically spawned based on a map file.

推荐答案

首先,加载所有这些图像确实是一个问题。 16乘16像素的1000个图像是256000个像素。即使每个像素使用4个字节也只会导致1 MB的图像数据,这并不多。

First, is loading all those images really a problem. 1000 images of 16 by 16 pixels are 256000 pixels. Even when using 4 bytes for each pixel would result in just one MB of image data, which isn't much.

如果你真的想要/需要减少数量您加载到内存中的图像,您只能将地图所需的可视图块/图像加载到内存中,还可以添加更多图像以增加游戏的响应速度。

If you really want/need to reduce the number of images you load into memory, you could only load the visual tiles/images needed for your map into memory, and a few more to increase responsiveness for your game.

例如如果你的游戏显示 n 的地图 m tiles,你可以加载一个 n + 2 m + 2 将内容块添加到内存中,或以可视方式表示(其中*是可见的图块和+额外加载的图块到内存中):

For example if your game shows a map of n by m tiles, you could load a n+2 by m+2 tiles into memory, or visually represented (where * are visible tiles and + the extra loaded tiles into memory):

+++++++++++
+*********+
+*********+
+*********+
+++++++++++

当用户移动地图时,您将删除对不再需要的图块的引用,并开始加载新图块。由于您在内存中保留了一个磁贴,因此移动地图仍应非常顺利。当然,如果您的瓷砖相当小,或者移动地图的速度相当快,您可以增加使用的额外瓷砖数量

When the user moves the map, you remove the references to the tiles you no longer need and start loading the new tiles. Since you have one tile in reserve in memory, moving the map should still happen quite smoothly. Of course, if your tiles are rather small, or moving the map happens pretty fast you can increase the number of extra tiles you use

这篇关于在Java中加载和缓存图像的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆