- procedure DrawLine(x1, y1, x2, y2: Integer);
- var
- x, y, DeltaX, DeltaY, HalfX, ErrorTerm, i: Integer;
- begin
- DeltaX := x2 - x1;
- DeltaY := y2 - y1;
- HalfX := (x2 - x1) shr 1;
- ErrorTerm := 0;
- x := x1;
- y := y1;
- for i:=0 to DeltaX do
- begin
- Plot(X, Y);
- Inc(x);
- ErrorTerm := ErrorTerm + DeltaY;
- if ErrorTerm>HalfX then
- begin
- ErrorTerm := ErrorTerm - DeltaX;
- Inc(y);
- end;
- end;
- end;
- 为方便阅读,上述程序作了简化。实际程序应略作修正,以分别处理DeltaX与DeltaY比较大小, 必要时交换起始、结束点等。
- 修正后的的伪Pascal算法如下:
- procedure DrawLine(x1, y1, x2, y2: Integer);
- var
- x, y, DeltaX, DeltaY, HalfCount, ErrorTerm, i, Flag: Integer;
- begin
- DeltaX := x2 - x1;
- DeltaY := y2 - y1;
- if Abs(DeltaY)<Abs(DeltaX) then
- begin
- if DeltaX<0 then
- begin
- i := x1; x1 := x2; x2 := i;
- i := y1; y1 := y2; y2 := i;
- DeltaX := x2 - x1;
- DeltaY := y2 - y1;
- end;
- if DeltaY<0 then Flag := -1
- else Flag := 1;
- DeltaY := Abs(DeltaY);
- HalfCount := DeltaX shr 1;
- ErrorTerm := 0;
- x := x1;
- y := y1;
- for i:=0 to DeltaX do
- begin
- Plot(X, Y);
- Inc(x);
- ErrorTerm := ErrorTerm + DeltaY;
- if ErrorTerm>HalfCount then
- begin
- ErrorTerm := ErrorTerm - DeltaX;
- y := y + Flag;
- end;
- end;
- end
- else
- begin
- if DeltaY<0 then
- begin
- i := x1; x1 := x2; x2 := i;
- i := y1; y1 := y2; y2 := i;
- DeltaX := x2 - x1;
- DeltaY := y2 - y1;
- end;
- if DeltaX<0 then Flag := -1
- else Flag := 1;
- DeltaX := Abs(DeltaX);
- HalfCount := DeltaY shr 1;
- ErrorTerm := 0;
- x := x1;
- y := y1;
- for i:=0 to DeltaY do
- begin
- Plot(X, Y);
- Inc(y);
- ErrorTerm := ErrorTerm + DeltaX;
- if ErrorTerm>HalfCount then
- begin
- ErrorTerm := ErrorTerm - DeltaY;
- x := x + Flag;
- end;
- end;
- end;
- end;