问题描述
我有这个精灵表:
如何读取此图像文件以提取其中的一部分以用作 sprite ?
How can I read this image file to extract part of it to be used as a sprite ?
推荐答案
如果精灵区域读入BufferedImage
,getSubimage
方法可用于获取子图像精灵表.
If the sprites area read into a BufferedImage
, the getSubimage
method can be used to get a subimage of the sprite sheet.
getSubimage
方法将采用 x
、y
、width
和 height
所需的子图像,因此可以获得所需的精灵.由于大多数精灵似乎大小相同,我认为它们中的大多数都可以通过嵌套的 for
循环来检索大图像.
The getSubimage
method will take the x
, y
, and the width
and height
of the desired subimage, so the desired sprite can be obtained. Since most of the sprites seem to be the same size, I would think most of them can be retrieved by a nested for
loop to iterate through the large image.
例如,如果使用 ImageIO
类(例如 read
方法),每个精灵的大小为 10 x 10 像素,其中 5 行 x 5 列的精灵,精灵可以通过以下方式获得:
For example, if the sprite image is loaded using the ImageIO
class (such as the read
method), and each sprite is 10 pixels by 10 pixels in size, where are 5 rows by 5 columns of sprites, the sprites can be obtained by the following:
BufferedImage bigImg = ImageIO.read(new File("sheet.png"));
// The above line throws an checked IOException which must be caught.
final int width = 10;
final int height = 10;
final int rows = 5;
final int cols = 5;
BufferedImage[] sprites = new BufferedImage[rows * cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
sprites[(i * cols) + j] = bigImg.getSubimage(
j * width,
i * height,
width,
height
);
}
}
当然,要注意的是,上述代码仅在所有精灵大小相同时才有效,因此需要进行一些调整才能对给定的精灵表起作用.(因为右上角似乎与其他角的大小不同.)
The catch is, of course, the above code will only work if all the sprites are the same size, so there will need to be some adjustment performed in order to work for the given sprite sheet. (As the top right-hand corner seems to be different in size from the others.)
这篇关于如何在 Java 中提取此图像的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!