DDA画线法(考虑所有情况)

使用了第三方图形库EGEv19.01,C++编写。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <cmath>
#include <graphics.h>
#include <iostream>
using namespace std;
void DDA_Line(int x0, int y0, int x1, int y1)
{
float dx, dy, k, x, y;
dx = x1 - x0;
dy = y1 - y0;
k = dy / dx;
if (dx == 0) {
//因为C++除法操作除数为零时候可能会出现undefined的结果
//简化后续if判断
k = 1000;
}
x = x0;
y = y0;
if (k > 0) {
if (dx > 0) {
//k>0且dx>0
if (dy < dx) {
//0<k<1,步进方向为x,y增量为k
for (; x <= x1; ++x) {
putpixel(x, int(y + 0.5), BLACK);
y += k;
}
} else {
//k>=1,步进方向为y,x增量为1/k
for (; y <= y1; ++y) {
putpixel(int(x + 0.5), y, BLACK);
x += 1 / k;
}
}
} else {
//k>0且dx<0,dy<0,此处判断反向画线
if (abs(dy) < abs(dx)) {
//0<k<1,步进方向为x,y增量为-k
for (; x >= x1; --x) {
putpixel(x, int(y + 0.5), BLACK);
y -= k;
}
} else {
//k>=1,步进方向为y,x增量为-1/k
for (; y >= y1; --y) {
putpixel(int(x + 0.5), y, BLACK);
x -= 1 / k;
}
}
}
} else {
if (dx > 0) {
//k<0且dx>0,dy<0
if (abs(dy) < abs(dx)) {
//-1<k<0,步进方向为x,y增量为k
for (; x <= x1; ++x) {
putpixel(x, int(y + 0.5), BLACK);
y += k;
}
} else {
//k<=-1,步进方向为y,x增量为1/k
for (; y >= y1; --y) {
putpixel(int(x + 0.5), y, BLACK);
x -= 1 / k;
}
}
} else {
//k<0且dx<0,dy>0,此处判断反向画线
if (abs(dy) < abs(dx)) {
//-1<k<0,步进方向为x,y增量为-k
for (; x >= x1; --x) {
putpixel(x, int(y + 0.5), BLACK);
y -= k;
}
} else {
//k>=-1,步进方向为y,x增量为-1/k
for (; y <= y1; ++y) {
putpixel(int(x + 0.5), y, BLACK);
x += 1 / k;
}
}
}
}
}

int main()
{
initgraph(640, 480);

setbkcolor(WHITE);
DDA_Line(30, 50, 10, 60); //-1<k<0
DDA_Line(10, 60, 30, 50);

DDA_Line(30, 50, 10, 90); //k<-1
DDA_Line(10, 90, 30, 50);

DDA_Line(30, 50, 10, 40); //0<k<1
DDA_Line(10, 40, 30, 50);

DDA_Line(30, 50, 10, 10); //k>1
DDA_Line(10, 10, 30, 50);

DDA_Line(10, 90, 10, 10); //k==0,x==10
DDA_Line(10, 10, 10, 90);

DDA_Line(30, 50, 10, 50); //k==0,y==50
DDA_Line(10, 50, 30, 50);

getch();

closegraph();
return 0;
}