我编写了一小段代码来将 Sprite 表分割成单独的图像......
private BufferedImage sheet, dirt, grass, rock, tree, water;
int width = 64, height = 64;
public void split() {
dirt = sheet.getSubimage(0,0,width,height);
grass = sheet.getSubimage(width,0,width*2,height);
rock = sheet.getSubimage(width*2,0,width*3,height);
tree = sheet.getSubimage(0,height,width,height*2);
water = sheet.getSubimage(width,height,width*2,height*2);
}
现在,前两个(泥土和草)如预期顺利进行。然而,问题在于岩石裁剪线。由于某种原因它会抛出异常...
”
线程“Thread-0”java.awt.image.RasterFormatException 中的异常:(x + width) 位于 Raster 之外
在 sun.awt.image.ByteInterleavedRaster.createWritableChild(ByteInterleavedRaster.java:1245)
"
很明显,问题与 x 值“越界”有关。但 x 值是(宽度 * 2),即 128pix,这完全在该图像(192x128)的范围内,我已将其作为证据附在其中。
我还对代码进行了一些更改,以将岩石的 x 值为 1 进行裁剪,但我仍然遇到问题,与对另一个 bufferedImage 使用相同的尺寸相同。
第一次发帖,有什么不对的地方请见谅。
提前致谢
最佳答案
回答我的评论。
所以您走在正确的道路上,但不太了解 getSubimage()
的工作原理。
文档说
Parameters:
x - the X coordinate of the upper-left corner of the specified rectangular region
y - the Y coordinate of the upper-left corner of the specified rectangular region
w - the width of the specified rectangular region
h - the height of the specified rectangular region
您正确设置了 x
和 y
值,但是您错误地设置了 width
和 height
> 值(value)观。
由于您从点 (x,y)
开始,因此不需要像您一样补偿 宽度
和 高度
,而不是直接使用它们。
所以,你的代码将是
public void split() {
dirt = sheet.getSubimage(0,0,width,height);
grass = sheet.getSubimage(width,0,width,height);
rock = sheet.getSubimage(width*2,0,width,height);
tree = sheet.getSubimage(0,height,width,height);
water = sheet.getSubimage(width,height,width,height);
}
关于java - getSubimage() 方法中出现越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39651319/