cpp实现直线的DDA算法
给定起始点,输出直线在两点之内所经过的像素点的位置。
比如输入:
输出起点x值:0
输出起点y值:0
输出终点x值:5
输出终点y值:2
输出结果:
(0,0)
(1,0)
(2,1)
(3,1)
(4,2)
(5,2)
代码如下:
#include<iostream>
using namespace std;
//直线的DDA算法
typedef struct point {
int x;
int y;
}point;
int myRound(double x);
void DDA(point* point1, point* point2);
int main() {
point* point1 = new point;
point* point2 = new point;
//输入两点坐标
cin >> point1->x >> point1->y >> point2->x >> point2->y;
DDA(point1, point2);
return 0;
}
int myRound(double x) {
return x > 0.0 ? int(x + 0.5) : int(x - 0.5);
}
void DDA(point* p1, point* p2) {
//斜率不存在
if (p1->x == p2->x) {
int min = (p1->y > p2->y) ? p2->y : p1->y;
int max = (p1->y < p2->y) ? p2->y : p1->y;
for (int i = min; i <= max; i++)
cout << "(" << p1->x << "," << i << ")" << endl;
}
else {
//计算斜率
double k = ((double)p2->y - p1->y) / ((double)p2->x - p1->x);
//x递增1
if (abs(k) <= 1) {
//确定起始点:x值小的为起点
point* p_first = (p1->x > p2->x) ? p2 : p1;
point* p_last = (p1->x < p2->x) ? p2 : p1;
double y = p_first->y;
for (int i = p_first->x; i <= p_last->x; i++,y += k) {
cout << "(" << i<< "," << myRound(y) << ")" << endl;
}
}
//y递增1
else {
//确定起始点:y值小的为起点
point* p_first = (p1->y > p2->y) ? p2 : p1;
point* p_last = (p1->y < p2->y) ? p2 : p1;
double x = p_first->x;
for (int i = p_first->y; i <= p_last->y; i++,x += 1/k) {
cout << "(" << myRound(x) << "," << i << ")" << endl;
}
}
}
};