2

用红点在 2PI 上绘制的正弦波图像 我应该使用 OpenGL_POINTS 绘制一个正弦波(如图像中的那个)。但是,在通过代码中的循环之后,我一直只得到一个点。

这是我的代码。

#include "stdafx.h"
#include <iostream>
#include <gl\GLUT.h>
#include <math.h>

using namespace std;

void RenderSineWave()
{
    int i;  
float x,y;  
glClearColor(0.0, 0.0, 0.0, 1.0);  // clear background with black
glClear(GL_COLOR_BUFFER_BIT);   

    glPointSize(10);
    glColor3f(1.0,0.0,0.0);


        for(i=0;i<361;i=i+5)
        {

            x = (float)i; 
            y = 100.0 * sin(i *(6.284/360.0));
            glBegin(GL_POINTS);
            glVertex2f(x,y);
            glEnd();
        glFlush();
        glutPostRedisplay();
        }

}

void main(int argc, char** argv)
{
    glutInit(&argc,argv);
    glutCreateWindow("SineWave.cpp");
glutDisplayFunc(RenderSineWave);
glutMainLoop();

}
4

2 回答 2

6

尝试设置一个合理的投影矩阵:

#include <GL/glut.h>
#include <cmath>

using namespace std;

void RenderSineWave()
{
    glClearColor(0.0, 0.0, 0.0, 1.0);  // clear background with black
    glClear(GL_COLOR_BUFFER_BIT);   

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    double w = glutGet( GLUT_WINDOW_WIDTH );
    double h = glutGet( GLUT_WINDOW_HEIGHT );
    double ar = w / h;
    glOrtho( -360 * ar, 360 * ar, -120, 120, -1, 1 );

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    glPointSize(10);
    glColor3f(1.0,0.0,0.0);

    glBegin(GL_POINTS);
    for(int i=0;i<361;i=i+5)
    {
        float x = (float)i; 
        float y = 100.0 * sin(i *(6.284/360.0));
        glVertex2f(x,y);
    }
    glEnd();

    glutSwapBuffers();
}

int main(int argc, char** argv)
{
    glutInit( &argc, argv );
    glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
    glutInitWindowSize( 640, 480 );
    glutCreateWindow( "SineWave.cpp" );
    glutDisplayFunc( RenderSineWave );
    glutMainLoop();
    return 0;
}
于 2013-10-15T16:42:23.137 回答
4

在前面加上这行glutMainLoop();告诉OpenGL在-1365inx之间、-200200in之间进行绘制y(默认太小看不到整个形状):

gluOrtho2D(-1,365,-200,200);

另外,删除线glutPostRedisplay();,否则您的屏幕可能会闪烁。

于 2013-10-15T16:39:30.197 回答