中点Bresenham算法c语言代码实现
时间: 2024-09-23 21:15:41 浏览: 47
中点Bresenham算法作椭圆
中点Bresenham算法是一种用于在计算机图形学中绘制直线的高效算法,它避免了除法运算,适用于像素坐标的情况。以下是C语言的基本实现:
```c
#include <stdio.h>
#include <math.h>
void draw_line(int x1, int y1, int x2, int y2) {
int dx = abs(x2 - x1);
int dy = abs(y2 - y1);
int steep = (dy > dx);
if (steep) {
// 如果y轴变化大于x轴,先交换x和y坐标
int temp = x1;
x1 = y1;
y1 = temp;
// 计算斜率的整数部分
int swapped_dx = dx;
dx = dy;
dy = swapped_dx;
}
if (dx > dy) {
// 对于x变化大于y的部分,每次增加x
for (int x = x1; x <= x2; x++) {
if (steep)
printf("%d %d\n", y1, x);
else
printf("%d %d\n", x, y1);
y1 += dy;
}
} else {
// 对于y变化大于x的部分,每次增加y
for (int y = y1; y <= y2; y++) {
if (steep)
printf("%d %d\n", x1, y);
else
printf("%d %d\n", y, x1);
x1 += dx;
}
}
}
int main() {
int x1, y1, x2, y2;
printf("Enter the starting point (x1 y1): ");
scanf("%d %d", &x1, &y1);
printf("Enter the ending point (x2 y2): ");
scanf("%d %d", &x2, &y2);
draw_line(x1, y1, x2, y2);
return 0;
}
```
阅读全文