如果我描述的形状像半圈关闭而另一半圈与第一圈相连,我怎么能画出形状像(sin)。使用笛卡尔方法这是我的尝试:
#include <windows.h>
#include <gl/Gl.h>
#include <gl/glut.h>
#include<math.h>
#include<cstdlib>
static void myDisplay()
{
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glColor3f(1.0,0.0,0.0);
glColor3f(0.0,0.0,0.0);
glBegin(GL_LINE_LOOP);
double xc=200, yc=200,r=100;
double x,y;
for (x = xc - r; x<= xc + r;x++)
{
y = sqrt((r*r)-((xc - x)*(xc - x)));
glVertex2d(x, yc + y);
}
for (x = xc +r ; x<= xc - r ; x++)
{
y = sqrt((r*r)-((xc - x)*(xc - x)));
glVertex2d(x , yc - y);
}
glEnd();
glFlush();
}
void myInit(void)
{
glClearColor(1.0,1.0,1.0,0.0); // set white background color
glColor3f(0.0f, 0.0f, 0.0f); // set the drawing color
glPointSize(4.0); // a ‘dot’ is 4 by 4 pixels
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
void main(int argc, char** argv)
{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(640,480); // set window size
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("Line Scan Conversion"); // open the screen window
glutDisplayFunc(myDisplay); // register redraw function
myInit();
glutMainLoop(); // go into a perpetual loop
}
答案 0 :(得分:0)
直接对函数(sin()
)进行采样:
#include <GL/glut.h>
#include <cmath>
static void myDisplay()
{
glClearColor( 0, 0, 0, 1 ); // set white background color
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho( -0.5, 7, -1.2, 1.2, -1, 1 );
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// axes
glColor3ub( 255, 255, 255 );
glBegin( GL_LINES );
glVertex2i( 0, 0 );
glVertex2i( 7, 0 );
glVertex2i( 0, -1 );
glVertex2i( 0, 1 );
glEnd();
// sin() function plot
glColor3ub( 255, 0, 0 );
glBegin(GL_LINE_STRIP);
const unsigned int samples = 100;
for( unsigned int i = 0; i <= samples; ++i )
{
const float pct = ( (float)i / samples );
const float x = 2 * 3.14159 * pct;
const float y = sin( x );
glVertex2f( x, y );
}
glEnd();
glutSwapBuffers();
}
void main(int argc, char** argv)
{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); // set display mode
glutInitWindowSize(600, 600); // set window size
glutCreateWindow("Line Scan Conversion"); // open the screen window
glutDisplayFunc(myDisplay); // register redraw function
glutMainLoop(); // go into a perpetual loop
}
答案 1 :(得分:0)
您的第二个for
循环中存在问题:
for( x = xc + r; x <= xc - r; x++ )
这是以x = 400; x <= 0; x++
执行的,显然永远不会运行。您的问题(除了上面明确指出的问题之外)是您试图在循环迭代中考虑x
偏移量。我建议改为:
for( x = 0; x < 2r; x++ )
然后代替
glVertex2d(x, yc + y);
glVertex2d(x, yc - y);
DO
glVertex2d((xc - r) + x, yc + y);
glVertex2d((xc + r) + x, yc - y);
或类似的东西(不能实际测试这个,但你应该明白这一点。)