glutBitmapCharacter定位文本错误

时间:2012-02-24 12:33:35

标签: c++ opengl glut

我正在尝试在屏幕上绘制一个简单的字符串(叠加)。

根据我在互联网上发现的内容,我正在以这种方式使用它:

void write(string text, int x, int y){
    glRasterPos2i(x,y);

    for(int i = 0; i < text.length(); i++){ 
        glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, text.data()[i]);
    }
}

但它根据世界坐标绘制字符串。比如说,如果x和y设置为10,它们将被绘制在世界的(10,10,0)坐标处。但我简单地需要在2D的窗口(10,10)坐标处使用此字符串。

这是一个小项目的一部分,绘制方法如下。我不想改变它,因为它可能会打破项目中的其他东西。

void disp(){
 // set viewing translation and object rotations
 glMatrixMode( GL_MODELVIEW );
 glLoadIdentity ();
 glTranslatef( INIT_VIEW_X, INIT_VIEW_Y, INIT_VIEW_Z );
 glRotatef( xRot, 1.0, 0.0, 0.0 );
 glRotatef( zRot, 0.0, 0.0, 1.0 );
 glScalef( scaleFactor, scaleFactor, scaleFactor );
 glClear(GL_COLOR_BUFFER_BIT);
 draw();
 glFlush();
}

我也不完全知道他们做了什么,我认为将文本绘制到世界坐标与此代码中的某些内容有关。我也试过了Using GLUT bitmap fonts,但它也不起作用。

我怎样才能简单地在屏幕上绘图。 OpenGL过度复杂化了;我试着简单地写到窗口,但它需要整个过程并转换为3D世界。我只是不想要这个。

3 个答案:

答案 0 :(得分:7)

从twall,是的,您需要清除模型视图和投影矩阵

//TEXT
glMatrixMode( GL_PROJECTION ) ;
glPushMatrix() ; // save
glLoadIdentity();// and clear
glMatrixMode( GL_MODELVIEW ) ;
glPushMatrix() ;
glLoadIdentity() ;

glDisable( GL_DEPTH_TEST ) ; // also disable the depth test so renders on top

glRasterPos2f( 0,0 ) ; // center of screen. (-1,0) is center left.
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
char buf[300];
sprintf( buf, "Oh hello" ) ;
const char * p = buf ;
do glutBitmapCharacter( GLUT_BITMAP_HELVETICA_18, *p ); while( *(++p) ) ;

glEnable( GL_DEPTH_TEST ) ; // Turn depth testing back on

glMatrixMode( GL_PROJECTION ) ;
glPopMatrix() ; // revert back to the matrix I had before.
glMatrixMode( GL_MODELVIEW ) ;
glPopMatrix() ;

答案 1 :(得分:0)

您可以退回到“2D”坐标,如下所示:

//save your current matrix on the stack, so you don't lose it
glPushMatrix();
//load identity matrix, so you don't have any 3d transformations
glLoadIdentity ();
//now you also can transform the text
//to the position just as you like
//glTransformf( ... )
//make sure the text is draw, even though it might be outside the viewing area
glDisable( GL_DEPTH_TEST )
drawMyFunkyText();
glEnable( GL_DEPTH_TEST )
//restore the matrix as it was before,
//so you can draw all your shapes as before
glPopMatrix();

答案 2 :(得分:0)

从我可以收集的内容来看,你所追求的是orthographic projection.

我不确定OpenGL(我已经习惯了更高级别的图形库),但是这里有几个链接可以作为起点:

Setting a orthographic projection matrix?

http://www.cprogramming.com/tutorial/opengl_projections.html