视频加载失败

课程

713 字
约 3 分钟

3.2 直线光栅化 - 中点画线算法

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

3.2 直线光栅化 - 中点画线算法

1. 任务描述

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

本关任务

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

输入

  1. 直线两端点坐标:(100, 100)(520, 300)
  2. 直线颜色为红色。

预期输出

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

相关知识

1. 绘制点函数

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

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

2. 中点画线算法

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

操作说明

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

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

2. 我的回答

文件 step4/test4.cpp:

#include "tgaimage.h"
#include <cstdlib>   // for std::abs
#include <algorithm> // for std::swap

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 **/
    bool steep = false;
    // 若斜率绝对值大于1,交换x和y,使基本增量在x方向
    if (std::abs(x1 - x0) < std::abs(y1 - y0)) {
        std::swap(x0, y0);
        std::swap(x1, y1);
        steep = true;
    }
    // 确保从左向右绘制
    if (x0 > x1) {
        std::swap(x0, x1);
        std::swap(y0, y1);
    }

    int dx = x1 - x0;
    int dy = y1 - y0;
    // 根据斜率0<k<1,dy为正值或负值,但决策参数基于绝对值增量
    int stepY = (dy > 0) ? 1 : -1;
    dy = std::abs(dy);

    int d = 2 * dy - dx;       // 初始决策参数
    int incrE = 2 * dy;        // 东向增量
    int incrNE = 2 * (dy - dx);// 东北向增量

    int y = y0;
    for (int x = x0; x <= x1; ++x) {
        if (steep) {
            image.set(y, x, color);   // 还原交换后的坐标
        } else {
            image.set(x, y, color);
        }
        if (d <= 0) {
            d += incrE;               // 选择E点
        } else {
            y += stepY;
            d += incrNE;              // 选择NE点,即直线上方点
        }
    }
    /**** End */
}

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