视频加载失败

课程

738 字
约 3 分钟

3.3 直线光栅化 - Bresenham 画线算法

计算机图形学labs/lab03-line-rasterization·更新于 2026-09-15

3.3 直线光栅化 - Bresenham 画线算法

1. 任务描述

根据下面要求,在右侧修改代码空间,绘制出预期输出的图片。平台会对你编写的代码进行测试。

本关任务

  1. 根据直线 Bresenham 算法补全 line() 函数,其中直线斜率满足 0 < k < 1,并将 main() 函数中的 line() 函数参数补充完整。
  2. 当直线方程恰好经过 P(x, y)T(x, y + 1) 的中点 M 时,统一选取直线上方的 T 点为显示的像素点。

输入

  1. 直线两端点坐标:(20, 20)(180, 140)
  2. 直线颜色为白色。

预期输出

程序运行结果为一条直线,具体结果如下图所示: 预期输出

相关知识

1. 绘制点函数

image.set(x, y, color) 函数是绘制点的函数,参数包括 x, ycolor

  • x:绘制点的 x 坐标。
  • y:绘制点的 y 坐标。
  • color:绘制点的颜色。

2. Bresenham 算法

Bresenham 算法相关知识点,请参考教材与课件或有关资料。

操作说明

  1. 按要求补全 line 函数和 main 函数中的调用。
  2. 点击窗口右下角“测评”按钮,等待测评结果,如果通过后可进行下一关任务。

开始你的任务吧,祝你成功!

2. 我的回答

文件 step2/test2.cpp:

#include "tgaimage.h"

const TGAColor white = TGAColor(255, 255, 255, 255);
const TGAColor red = TGAColor(255, 0, 0, 255);

void line(int x0, int y0, int x1, int y1, TGAImage &image, TGAColor color)
{
    // Please add the code here
    /**** Begin **/
    int dx = x1 - x0;
    int dy = y1 - y0;
    int p = 2 * dy - dx; // 初始化决策参数
    int y = y0;
    
    for (int x = x0; x <= x1; x++) {
        image.set(x, y, color); // 绘制当前点
        
        // 当 p >= 0 时,说明真实直线交点在中点或中点上方
        // 题目要求:恰好经过中点时(p == 0),选取直线上方的T点,即 y 需要增加
        if (p >= 0) {
            y++;
            p += 2 * dy - 2 * dx;
        } else {
            p += 2 * dy;
        }
    }
    /** End */
}

int main(int argc, char** argv)
{
    TGAImage image(640,480, TGAImage::RGB);
    
    // Please add the code here
    /**** Begin **/
    // 传入起点(20, 20)、终点(180, 140)以及白色(white)
    line(20, 20, 180, 140, image, white);
    /** End */
    
    image.flip_vertically(); // i want to have the origin at the left bottom corner of the image
    image.write_tga_file("../img_step2/test.tga");
    return 0;
}
Profile Image of the Author
Sonder
好想要技术
这是公告标题
这只是一个公告
分类
标签
站点信息
构建平台
GitHub Actions
博客版本
Firefly v6.16.7
文章许可
CC BY-NC-SA 4.0
文章目录