如果将精灵区域读取为BufferedImage
,则该getSubimage
方法可用于获取精灵表的子图像。
该getSubimage
方法将采取x
,y
以及width
和height
期望的子图像,从而能够得到所希望的子画面。由于大多数精灵的大小似乎相同,因此我认为可以通过嵌套for
循环来检索大多数精灵,以遍历大图像。
例如,如果使用ImageIO
类(例如read
方法)加载子画面图像,并且每个子画面的大小为10像素乘10像素,其中5行乘5列子画面,则可以通过以下方式获得子画面:
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
);
}
}
当然,要注意的是,以上代码仅在所有精灵大小相同的情况下才有效,因此需要进行一些调整才能对给定的精灵工作。(由于右上角的尺寸似乎与其他尺寸不同。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句