源文件在最底部。

画线算法代码:

void line_bresenham(int x0, int y0, int x1, int y1, TGAImage& image, TGAColor& color)
{
    int dx = x1 - x0; // 两点之间的水平距离
    int dy = y1 - y0; // 两点之间的垂直距离
    bool is_steep = false; // 直线的斜率是否大于 45 度?

    // 判断直线的斜率是否大于 45 度,如果是则需要按 y = x 对称
    if (abs(dx) < abs(dy)){
        is_steep = true;
        swap(x0, y0);
        swap(x1, y1);
    }

    // 确保 x0 <= x1
    if (x0 > x1){
        swap(x0, x1);
        swap(y0, y1);
    }

    dx = x1 - x0;
    dy = y1 - y0;

    int sum_error = 0; // 跟踪算法的误差
    int delta_error = abs(dy) * 2; // x 方向每前进一步时误差的变化量
    int y = y0;// 当前的 y 坐标

    for (int x = x0; x <= x1; x++)
    {
        // 根据是否需要对称去绘制像素点
        is_steep ? image.set(y, x, color) : image.set(x, y, color);
        // 更新误差
        sum_error += delta_error;
        // 如果误差超过dx,根据斜率的正负来决定y坐标增加或者减少。并更新误差
        if (sum_error > dx)
        {
            y += (y1 > y0 ? 1 : -1);
            sum_error -= 2 * dx;
        }
    }
}

main函数:

#include "tgaimage.h"
#include "model.h"
#include "geometry.h"
using namespace std;

const int width = 800;
const int height = 800;

int main()
{
	TGAImage image(width, height, TGAImage::RGB);

	TGAColor green = TGAColor(0, 255, 0, 0);

  int x0 = 0, y0 = 500, x1 = 1000, y1 = 0;

	line_bresenham(x0, y0, x1, y1, image, green);

	image.write_tga_file("line_bresenham.tga");

	return 0;
}

源文件:

main.cpp