我有一个 ByteBuffer,其中存储任意尺寸的 RGBA 图像。我试图用单一、随机、RGBA 颜色的三角形覆盖该图像的某些部分。但是,我收到了 IndexOutOfBoundsException,这对我来说没有意义。
public ByteBuffer getByteBuffer()
{
/*Creates a ByteBuffer containing an image of a single background colour. A single pixel in the image is
represented as a float array of size 4*/
ByteBuffer buffer = Helpers.getBGByteBuffer(new float[]{1f, 1f, 1f, 1f}, width * height * 4 * Float.BYTES);
ByteBuffer triBuffer;
int offset;
for(RenderTriangle triangle : triangleList)
{
offset = triangle.getOffset().y; //Indicates the offset (position) of the triangle in relation to the image
triBuffer = triangle.getByteBuffer(); //Gets the ByteBuffer of the triangle.
for(int i = 0; i < triBuffer.capacity(); i += 4 * Float.BYTES) //Float.BYTES = 4
{
byte[] rgba1 = new byte[4 * Float.BYTES];
byte[] rgba2 = new byte[4 * Float.BYTES];
triBuffer.get(rgba1, i, rgba1.length); //Throws exception for i = 16
buffer.get(rgba2, offset + i, rgba2.length);
byte[] rgbaAdded = Helpers.addBytesAsFloats(rgba1, rgba2); //Calculates resulting RGBA value
buffer = buffer.put(rgbaAdded, offset + i, rgbaAdded.length);
}
}
return buffer;
}
上面的代码在 for 循环的第二次迭代(因此 i = 16)处抛出异常
triBuffer.get(rgba1, i, rgba1.length),
第二次迭代时,抛出异常之前的一些相关调试值:
offset = 0
i = 16
rgba1 = {byte[16]@xxx}
rgba2 = {byte[16]@xxx}
triBuffer = {HeapByteBuffer@xxx}"java.nio.HeapByteBuffer[pos=16 lim=64 cap=64]"
buffer = {HeapByteBuffer@xxx}"java.nio.HeapByteBuffer[pos=32 lim=64 cap=64]"
最佳答案
我认为该行不正确。
由于 ByteBuffer 是一个缓冲区,它使用自己的索引来跟踪它所在的位置,因此当您读取 16 个字节时,下次读取时,您将读取接下来的 16 个字节(您不会回到开头)。
在您的行中,i
参数实际上代表要插入的目标数组的位置。
所以我认为正确的行应该是:triBuffer.get(rgba1, 0, rgba1.length)
也许您需要对其他 ByteBuffer 执行相同的操作,我不确定。
关于java - ByteBuffer 越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33694298/