CG2-v2.0-三角形填充
第一关.扫描线填充法
一. 任务描述
1. 本关任务
了解和掌握扫描线填充法,实现对三角形区域进行填充,具体要求如下: (1) 补全triangle函数; (2) 将main函数中的三角形顶点坐标和triangle函数参数补充完整。
2. 输入
(1) 三角形的三个顶点的坐标:
t0 = {125,50}, t1 = {300,200}, t2 ={200,350};
(2) 三角形区域为蓝色。
3. 输出程序运行结果为一个蓝色三角形区域,如下图所示:
#include "pngimage.h"
#include<stdio.h>
#include <iostream>
struct Vec2i
{
int x, y;
};
void triangle(Vec2i t0, Vec2i t1, Vec2i t2, PNGImage& image, PNGColor color) {
// Please add your code here
/********** Begin ********/
if (t0.y>t1.y) std::swap(t0, t1);
if (t0.y>t2.y) std::swap(t0, t2);
if (t1.y>t2.y) std::swap(t1, t2);
int total_height = t2.y-t0.y;
for (int y=t0.y; y<=t1.y; y++) {
int segment_height = t1.y-t0.y+1; //be careful with divisions by zero
float alpha = (float)(y-t0.y)/total_height; //edge t0t2
float beta = (float)(y-t0.y)/segment_height; //edge t0t1
Vec2i A,B;
A.y=B.y=y;
A.x = t0.x + (t2.x-t0.x)*alpha;
B.x = t0.x + (t1.x-t0.x)*beta;
if (A.x>B.x) std::swap(A.x, B.x);
for (int x=A.x; x<=B.x; x++) {
image.set(x, y, color);
}
}
for (int y = t1.y; y <= t2.y; y++)//感觉这个就是上半部分。
{
int segment_height = t2.y-t1.y+1;
float alpha2 = (float)(y-t0.y)/total_height; //edge t0t2
float beta2 = (float)(y-t1.y)/segment_height; //edge t0t1
Vec2i A2,B2;
A2.y=B2.y=y;
A2.x = t0.x + (t2.x-t0.x)*alpha2;
B2.x = t1.x - (t1.x-t2.x)*beta2;
if (A2.x>