计算机图形与OpenGL学习四(2.画圆算法)

圆生成算法

公式太多,转为图片格式





【代码】

#include<GL/glut.h>
#include<math.h>
#include<Windows.h>
#include<iostream>
#include<stdlib.h>
using namespace std;
GLsizei winWidth = 500, winHeight = 500;
GLuint regHex;//显示表标识
GLint xc,yc;
GLint radius;
class screenPt
{
private:
	GLint x, y;
public:
	screenPt()
	{
		x = y = 0;
	}
	void setCoords(GLint xcord, GLint ycord)
	{
		x = xcord;
		y = ycord;
	}
	GLint getXcord()
	{
		return x;
	}
	GLint getYcord()
	{
		return y;
	}
	void incrementx()
	{
		x++;
	}
	void decrementy()
	{
		y--;
	}
};
void setPixel(GLint x, GLint y)
{
	
	glBegin(GL_POINTS);
	glVertex2i(x, y);
	glEnd();
}
void circlePoints(GLint xc, GLint yc, screenPt circPt)
{
	
	setPixel(xc + circPt.getXcord(), yc + circPt.getYcord());
	setPixel(xc - circPt.getXcord(), yc + circPt.getYcord());
	setPixel(xc + circPt.getXcord(), yc - circPt.getYcord());
	setPixel(xc - circPt.getXcord(), yc - circPt.getYcord());
	setPixel(xc + circPt.getYcord(), yc + circPt.getXcord());
	setPixel(xc - circPt.getYcord(), yc + circPt.getXcord());
	setPixel(xc + circPt.getYcord(), yc - circPt.getXcord());
	setPixel(xc - circPt.getYcord(), yc - circPt.getXcord());
}
void circMidPoint(GLint xc, GLint yc, GLint radius)
{
	
	screenPt cirPt;
	cout << "radius" << radius << endl;
	cirPt.setCoords(0, radius);//初始点
	GLint p = 1 - radius;//初始p
	circlePoints(xc, yc, cirPt);
	cout << cirPt.getXcord() << "," << cirPt.getYcord() << endl;
	while (cirPt.getXcord() < cirPt.getYcord())
	{
		cout << "进入while" << endl;
		cirPt.incrementx();
		if (p < 0)
		{
			p += 2 * cirPt.getXcord() + 1;
		}
		else
		{
			cirPt.decrementy();
			p += 2 * (cirPt.getXcord() - cirPt.getYcord()) + 1;
		}
		circlePoints(xc, yc, cirPt);
		cout << "当前像素点为" << cirPt.getXcord() << "," << cirPt.getYcord() << endl;
	}

}

static void init(void)
{
	//初始化函数,并加入表

	glClearColor(1.0, 1.0, 1.0, 0.0);//设置为白色背景
	regHex = glGenLists(1);//获得一个标识

	glNewList(regHex, GL_COMPILE);
	glColor3f(1.0, 0.0,0.0);
	glPointSize(5);
	circMidPoint(xc, yc, radius);
	glEndList();

}

void circlePlot(void)
{
	//画圆
	glClear(GL_COLOR_BUFFER_BIT);
	glCallList(regHex);//显示表
	glFlush();
}

void winReshapeFcn(int newWidth, int newHeight)
{
	//窗口重定形函数
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();//将当前的用户坐标系的原点移到了屏幕中心:类似于一个复位操作
	gluOrtho2D(0.0, (GLdouble)newWidth, 0.0, (GLdouble)newWidth);
	glClear(GL_COLOR_BUFFER_BIT);


} int main(int argc, char**argv)
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
	glutInitWindowPosition(100, 100);
	glutInitWindowSize(winWidth, winHeight);
	glutCreateWindow("Example");
	cout << "输入圆心坐标(范围为0-500,0-500):" << endl;
	cin >> xc >> yc;

	cout << "输入半径" << endl;
	cin >> radius;
	init();
	glutDisplayFunc(circlePlot);
	glutReshapeFunc(winReshapeFcn);
	glutMainLoop();
	return 0;
}

【结果】

圆心坐标(200,200)半径100


猜你喜欢

转载自blog.csdn.net/lhs322/article/details/79900736