如何在 C++ 中使用 glutBitmapString() 将文本绘制到屏幕上?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/544079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:52:51  来源:igfitidea点击:

How do I use glutBitmapString() in C++ to draw text to the screen?

c++graphicsglut

提问by KingNestor

I'm attempting to draw text to the screen using GLUT in 2d.

我正在尝试在 2d 中使用 GLUT 将文本绘制到屏幕上。

I want to use glutBitmapString(), can someone show me a simple example of what you have to do to setup and properly use this method in C++ so I can draw an arbitrary string at an (X,Y) position?

我想使用 glutBitmapString(),有人可以向我展示一个简单的示例,说明在 C++ 中设置和正确使用此方法必须执行的操作,以便我可以在 (X,Y) 位置绘制任意字符串?

glutBitmapString(void *font, const unsigned char *string); 

I'm using linux, and I know I need to create a Font object, although I'm not sure exactly how and I can supply it with the string as the second arguement. However, how do I also specify the x/y position?

我正在使用 linux,并且我知道我需要创建一个 Font 对象,尽管我不确定如何以及我可以将字符串作为第二个参数提供给它。但是,我如何还指定 x/y 位置?

A quick example of this would help me greatly. If you can show me from creating the font, to calling the method that would be best.

一个简单的例子会对我有很大帮助。如果你能告诉我从创建字体到调用最好的方法。

回答by Adam Rosenfield

You have to use glRasterPosto set the raster position before calling glutBitmapString(). Note that each call to glutBitmapString()advances the raster position, so several consecutive calls will print out the strings one after another. You can also set the text color by using glColor(). The set of available fonts are listed here.

glRasterPos在调用之前,您必须使用来设置光栅位置glutBitmapString()。请注意,每次调用都会glutBitmapString()推进光栅位置,因此多次连续调用将一个接一个地打印出字符串。您还可以使用 设置文本颜色glColor()此处列出了可用字体集。

// Draw blue text at screen coordinates (100, 120), where (0, 0) is the top-left of the
// screen in an 18-point Helvetica font
glRasterPos2i(100, 120);
glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
glutBitmapString(GLUT_BITMAP_HELVETICA_18, "text to render");

回答by Vishal Gupta

Adding to Adam's answer,

添加到亚当的答案,

glColor4f(0.0f, 0.0f, 1.0f, 1.0f);  //RGBA values of text color
glRasterPos2i(100, 120);            //Top left corner of text
const unsigned char* t = reinterpret_cast<const unsigned char *>("text to render");
// Since 2nd argument of glutBitmapString must be const unsigned char*
glutBitmapString(GLUT_BITMAP_HELVETICA_18,t);

Check out https://www.opengl.org/resources/libraries/glut/spec3/node76.htmlfor more font options

查看https://www.opengl.org/resources/libraries/glut/spec3/node76.html了解更多字体选项