实验三 图形填充

该代码示例展示了如何使用OpenGL和GLUT库在C++中实现4连接的边界填充算法。程序首先定义了一个颜色比较函数,然后在窗口中绘制一个蓝色三角形,并选择一个红色像素作为填充起点。通过递归地填充相邻像素,直到遇到边框颜色为止。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

#include <GL/glut.h>
#include <stdlib.h>
#include <math.h>
#include <windows.h>
#include <iostream>
using namespace std;
typedef float Color[3];

bool rgbColorEqual(Color c1, Color c2)
{
	if ( abs(c1[1] - c2[1]) < 0.001 && abs(c1[2] - c2[2]) < 0.001 && abs(c1[0] - c2[0]) < 0.001)
		return true;
	else
		return false;
}

void setPixel(GLint x, GLint y)
{
	glBegin(GL_POINTS);
	glVertex2i(x, y);
	glEnd();
	cout << x << "" << y << endl;
}

void getPixel(GLint x, GLint y, Color c)
{
	glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, c);
}

void boundaryFill4(int x, int y, Color fillColor, Color borderColor)
{
	Color interiorColor;

		getPixel(x, y, interiorColor);
		if (!(rgbColorEqual(interiorColor, borderColor)) && !(rgbColorEqual(interiorColor, fillColor)))
		{
			setPixel(x, y);
			Sleep(2);
			boundaryFill4(x + 1, y, fillColor, borderColor);  //右
			boundaryFill4(x - 1, y, fillColor, borderColor);  //左
			boundaryFill4(x , y+1 , fillColor, borderColor);  //上
			boundaryFill4(x , y-1 , fillColor, borderColor);  //下
		}
}

void init(void) 
{
	glClearColor(1.0, 10, 1.0, 0.0);
	glMatrixMode(GL_PROJECTION); //指定投影矩阵
	gluOrtho2D(0.0, 400.0, 0.0, 400.0); //指定显示的区域
}

void myDisplay(void)
{
	Color a = { 1.0 ,0.0 ,0.0 }, b = { 0.0,0.0,1.0 };
	glColor3fv(b);
	glClear(GL_COLOR_BUFFER_BIT);
	glBegin(GL_LINE_LOOP);
	glVertex2i(100, 100);
	glVertex2i(200, 100);
	glVertex2i(150, 150);
	glEnd();
	glColor3fv(a);
	boundaryFill4(150, 120, a, b);

	glFlush();
}

void main(int argc, char* argv[])
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
	glutInitWindowPosition(100, 100);
	glutInitWindowSize(400, 400);
	glutCreateWindow("窗口名称");
	init();
	glutDisplayFunc(&myDisplay);

	glutMainLoop();
}

结果图 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值