J2ME实现图形学之——中点划线法
J2ME实现图形学之——中点划线法 最近学习图形学,开始记录所学所长:
根据直线方程: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);
}
}
编译通过