完成bresenham's line
							parent
							
								
									22984c1c87
								
							
						
					
					
						commit
						9b753769b1
					
				| 
						 | 
					@ -3,9 +3,48 @@
 | 
				
			||||||
const TGAColor white = TGAColor(255, 255, 255, 255);
 | 
					const TGAColor white = TGAColor(255, 255, 255, 255);
 | 
				
			||||||
const TGAColor red = TGAColor(255, 0, 0, 255);
 | 
					const TGAColor red = TGAColor(255, 0, 0, 255);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					void line(int x0, int y0, int x1, int y1, TGAImage& image, TGAColor color) {
 | 
				
			||||||
 | 
						bool steep = false;
 | 
				
			||||||
 | 
						if (std::abs(x0-x1) < std::abs(y0-y1)) // 交换次序
 | 
				
			||||||
 | 
						{
 | 
				
			||||||
 | 
							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;
 | 
				
			||||||
 | 
						int derror2 = std::abs(dy) * 2;
 | 
				
			||||||
 | 
						int error2 = 0;
 | 
				
			||||||
 | 
						int y = y0;
 | 
				
			||||||
 | 
						for (int x = x0; x <=x1; x++)
 | 
				
			||||||
 | 
						{
 | 
				
			||||||
 | 
							if (steep) 
 | 
				
			||||||
 | 
							{
 | 
				
			||||||
 | 
								image.set(x, y, color);
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							else
 | 
				
			||||||
 | 
							{
 | 
				
			||||||
 | 
								image.set(x, y, color);
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							error2 += derror2;
 | 
				
			||||||
 | 
							if (error2 > dx) // 误差值,提供从当前位置到最佳直线的距离
 | 
				
			||||||
 | 
							{
 | 
				
			||||||
 | 
								y += (y1 > y0 ? 1 : -1);
 | 
				
			||||||
 | 
								error2 -= dx * 2;
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
int main(int argc, char** argv) {
 | 
					int main(int argc, char** argv) {
 | 
				
			||||||
	TGAImage image(100, 100, TGAImage::RGB);
 | 
						TGAImage image(100, 100, TGAImage::RGB);
 | 
				
			||||||
	image.set(52, 41, red);
 | 
						line(52, 41,90,70,image ,red);
 | 
				
			||||||
	image.flip_vertically(); // i want to have the origin at the left bottom corner of the image
 | 
						image.flip_vertically(); // i want to have the origin at the left bottom corner of the image
 | 
				
			||||||
	image.write_tga_file("output.tga");
 | 
						image.write_tga_file("output.tga");
 | 
				
			||||||
	return 0;
 | 
						return 0;
 | 
				
			||||||
| 
						 | 
					
 | 
				
			||||||
		Loading…
	
		Reference in New Issue