我正在尝试实现Bresenham线描算法(https://github.com/ssloy/tinyrenderer/wiki/Lesson-1:-Bresenham的-Line-Drawing-Algorithm),但是我不断收到Arrayindexoutofbounds异常,并且尝试通过它进行尝试是行不通的。有人知道导致异常的原因吗?
代码绘制了预期的内容,但是如果行超出了屏幕的底部,我将收到“线程“ Thread-2”中的异常java.lang.ArrayIndexOutOfBoundsException:480319”。我尝试过仅在屏幕上进行渲染,但这似乎不起作用。
public void drawLine(int x0, int y0, int x1, int y1, int col){
int temp = 0;
boolean steep = false;
if(abs(x0 - x1) < abs(y0 - y1)){
// Swap x0 and y0
temp = x0;
x0 = y0;
y0 = temp;
// Swap x1 and y1
temp = x1;
x1 = y1;
y1 = temp;
steep = true;
}
if(x0 > x1){
// Swap x0 and x1
temp = x0;
x0 = x1;
x1 = temp;
// Swap y0 and y1
temp = y0;
y0 = y1;
y1 = temp;
}
for(int x = x0; x <= x1; x++){
float t = (x - x0) / (float)(x1 - x0);
int y = (int)(y0 * (1.0f - t) + y1 * t);
if(steep){
// My attempt at fixing the problem
if(y < height){
pixels[y + x * width] = col;
}else{
y--;
}
}else{
// My attempt at fixing the problem
if(y < height){
pixels[x + y * width] = col;
}else{
y--;
}
}
}
}