Is there anyway to get it wholly accurate.
Consider the arguments: line(45, 45, 300, 12, REGION_X, REGION_Y, g);
It is just barely in region (8, 1) but the method doesn’t flag this region.
Or will it never happen because of using floats?
I fixed the accuracy problem with my version
private static final void line(int x0, int y0, int x1, int y1, int regionXSize, int regionYSize, Graphics g) {
int alternate = 0;
boolean steep = Math.abs(y1 - y0) > Math.abs(x1 - x0);
if (steep) {
int tmp = x0;
x0 = y0;
y0 = tmp;
tmp = x1;
x1 = y1;
y1 = tmp;
}
if (x0 > x1) {
int tmp = x0;
x0 = x1;
x1 = tmp;
tmp = y0;
y0 = y1;
y1 = tmp;
}
int deltax = x1 - x0;
int deltay = Math.abs(y1 - y0);
int error = deltax / 2;
int ystep = -1;
int y = y0;
if (y0 < y1)
ystep = 1;
for (int x = x0; x <= x1; x++) {
int absX;
int absY;
if (steep) {
absX = y;
absY = x;
} else {
absX = x;
absY = y;
}
int regX = absX / regionXSize;
int regY = absY / regionYSize;
if (absX < 0)
regX--;
if (absY < 0)
regY--;
g.setColor(alternate++ % 2 == 0 ? Color.green : new Color(0, 127, 0));
g.fillRect(regX * REGION_X, regY * REGION_Y, REGION_X, REGION_Y);
System.out.println(regX + " " + regY);
int dX;
int dY;
if (steep) {
dX = regionYSize - (absY - (regionYSize * regY));
dY = absX - (regionXSize * regX);
} else {
dX = regionXSize - (absX - (regionXSize * regX));
dY = absY - (regionYSize * regY);
}
int ceil = x + dX - 1;
for (; x < ceil; x++) {
error -= deltay;
if (error < 0) {
y += ystep;
error += deltax;
dY += ystep;
if (dY <= -1 || dY >= (steep ? regionXSize : regionYSize))
break;
}
}
}
}