画圆——方程算法

来源:互联网 发布:优先级调度算法流程图 编辑:程序博客网 时间:2024/05/17 22:03

1、圆的方程:
这里写图片描述

2、代码:

#include "stdafx.h"#include <windows.h>#include <GL/glu.h>#include <GL/gl.h>#include <GL/glut.h>#include<stdlib.h>  #include<math.h>void DrawCircle(int x, int y, int r){    int n = 20000;  //分成20000份    float increment = 2 * r * 1.0 / n; //每次x的增量    glBegin(GL_POINTS);    //上半个圆    float xCurrent = x - r;    float yCurrent = 0;    for (int i = 0; i <= n; ++i)    {        xCurrent += i*increment;        yCurrent = y + sqrtf(pow((float)r, 2) - pow((x - xCurrent), 2));        glVertex3f(xCurrent, yCurrent, 0);    }    //下半个圆    xCurrent = x - r;    yCurrent = 0;    for (int i = 0; i <= n; ++i)    {        xCurrent += i*increment;        yCurrent = y - sqrtf(pow((float)r, 2) - pow((x - xCurrent), 2));        glVertex3f(xCurrent, yCurrent, 0);    }    glEnd();    glFlush();}//主循环方法void display(void){    glClear(GL_COLOR_BUFFER_BIT);    glColor3f(1.0f, 0.0f, 1.0f);    gluOrtho2D(-500,500,-500,500); //屏幕的坐标左下角为(-500,500),右上角为(500,500)。    glPointSize(3);    DrawCircle(0, 0, 250); //半径为250}int main(int argc, char* argv[]){    glutInit(&argc, argv);    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);    glutInitWindowSize(400, 400);    glutInitWindowPosition(200, 200);    glutCreateWindow("Circle");    glutDisplayFunc(display);    glutMainLoop();    return(0);}

这样会有有一定的误差,右边的圆形会有几个点间断:
这里写图片描述

0 0
原创粉丝点击