圖形學實驗3——————簡單種子填充算法

容易溢出,我是用Release模式才運行成功的

#include <math.h>
#include <gl/glut.h>

struct Point {//點的位置
	GLint x;  //typedef int GLint 
	GLint y;
};

struct Color {//點的顏色信息
	GLfloat r;//typedef float GLfloat
	GLfloat g;
	GLfloat b;
};

void init() {//初始化
	glClearColor(1.0, 1.0, 1.0, 0.0);
	glColor3f(0.0, 0.0, 0.0);
	glPointSize(1.0);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0, 640, 0, 480);
}

Color getPixelColor(GLint x, GLint y) {//得到點(x,y)的顏色信息
	Color color;
	glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, &color);
	return color;
}

void setPixelColor(GLint x, GLint y, Color color) {//將點(x,y)顏色置爲color
	glColor3f(color.r, color.g, color.b);
	glBegin(GL_POINTS);
	glVertex2i(x, y);
	glEnd();
	glFlush();
}

void floodFill(GLint x, GLint y, Color oldColor, Color newColor) {
	Color color;
	color = getPixelColor(x, y);

	if (color.r == oldColor.r && color.g == oldColor.g && color.b == oldColor.b)
	{
		setPixelColor(x, y, newColor);
		floodFill(x + 1, y, oldColor, newColor);
		floodFill(x, y + 1, oldColor, newColor);
		floodFill(x - 1, y, oldColor, newColor);
		floodFill(x, y - 1, oldColor, newColor);
	}
	return;
}

void draw_circle(Point pC, GLfloat radius) {//畫一個圓
	GLfloat step = 1 / radius;
	GLfloat x, y;

	for (GLfloat theta = 0; theta <= 360; theta += step) {
		x = pC.x + (radius * cos(theta));
		y = pC.y + (radius * sin(theta));
		glVertex2i(x, y);
	}
}

void display(void) {
	Point pt = { 320, 240 };//圓心
	GLfloat radius = 50;    //半徑

	glClear(GL_COLOR_BUFFER_BIT);
	glBegin(GL_POINTS);     //開始畫圓
		draw_circle(pt, radius);
	glEnd();
	Color newColor = { 1.0f, 0.0f, 0.0f };//紅色
	Color oldColor = { 1.0f, 1.0f, 1.0f };//黑色

	floodFill(320, 240, oldColor, newColor);//填充
	glFlush();
}

int main(int argc, char** argv)
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
	glutInitWindowSize(640, 480);
	glutInitWindowPosition(200, 200);
	glutCreateWindow("畫圓!");
	init();
	glutDisplayFunc(display);
	glutMainLoop();
	return 0;
}

實驗結果
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章