最近學習圖形學,開始記錄所學所長:
根據直線方程:F(x, y) = ax + by + c = 0
其中, a = y0 - y1, b = x1 - x0, c = x0y1 - x1y0。
將中點代入函數得:
d = F(M) = F(xp + 1, yp + 0.5) = a(xp + 1) + b(yp + 0.5) + c
所以當d<0時, M在直線下方, 當d >= 0時, M在直線上方
采用增量法
d>=0時,取(xp+2, yp+0.5)
代入得:d1 = F(xp+2, yp+0.5) = a(xp+2)+b(yp+0.5)+c = d + a
故增量為a
d<0時,取(xp+2, yp+1.5) = a(xp+2)+b(yp+1.5)+c = d + a + b
故增量為b
d的初值:d0 = F(x0 + 1, y0 + 0.5) = a(x0 + 1) + b(y0 + 0.5) + c
= ax0 + by0 + c + a + 0.5b
= F(x0, y0) + a + 0.5b
因為F(x0, y0) = 0
所以d0 = a + 0.5b
只需要d的符號,所以用2d代替d
程序為:
public void MidpointLine(Graphics g, int x0, int y0, int x1, int y1, int color)
{
int a, b, delta1, delta2, d, x, y;
a = y0 - y1;
b = x1 - x0;
d = 2 * a + b;
delta1 = 2 * a;
delta2 = 2 * (a + b);
x = x0;
y = y0;
g.setColor (color);
g.drawLine(x, y, x, y);
while(x < x1)
{
if( d < 0)
{
x ++;
y ++;
d += delta2;
}
else
{
x ++;
d += delta1;
}
g.setColor (color);
g.drawLine(x, y, x, y);
}
}
編譯通過