c++ - 使用 OpenGL 将位图文本居中到矩形

标签 c++ opengl

我需要将一段文本置于矩形的中心。

我找到了这个 example ,但我很难理解它的作用。

实现这个并不难,我只需要知道绘制后如何找到文本的宽度和高度,但我无法在任何地方找到它。

为了绘制文本,我一个字符一个字符地绘制:

static void drawText(std::string str, float x, float y, float z) {
    glRasterPos3f(x, y, z);
    for (unsigned int i = 0; i < str.size(); i++) {
        glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, str[i]);
    }
}

不确定这是否是最好的方法,但这是我使用 OpenGL 的第一个程序。

最佳答案

光栅字体很糟糕,这在现代 OpenGL 中行不通,所以你知道 - 现在你需要使用纹理映射三角形来实现位图字体。如果您刚刚起步,旧版 OpenGL 可能适合您,但您会发现 OpenGL ES 和核心 OpenGL 3+ 不支持诸如光栅位置之类的东西。

也就是说,您可以对字符串中的所有字符求和 glutBitmapWidth (...),如下所示:

      unsigned int str_pel_width = 0;
const unsigned int str_len       = str.size ();

// Finding the string length can be expensive depending on implementation (e.g. in
//   a C-string it requires looping through the entire string storage until the
//     first null byte is found, each and every time you call this).
//
//  The string has a constant-length, so move this out of the loop for better
//    performance! You are using std::string, so this is not as big an issue, but
//      you did ask for the "best way" of doing something.

for (unsigned int i = 0; i < str_len; i++)
  str_pel_width += glutBitmapWidth (GLUT_BITMAP_HELVETICA_18, str [i]);

现在,要结束这个讨论,您应该知道在 GLUT 位图字体中每个字符的高度是相同的。如果我记得,18 pt。 Helvetica 可能有 22 或 24 像素高。 pt之间的区别。大小和像素大小应该用于 DPI 缩放,但 GLUT 实际上并没有实现这一点。

关于c++ - 使用 OpenGL 将位图文本居中到矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19213501/

相关文章:

c++ - 如果附加了 gdb,我该如何中断,但如果没有附加,我该如何继续?

c++ - 有关代码维护的建议

c++ - 如何正确填充顶点数组

c++ - C++ RAII 类中的 OpenGL 对象不再有效

c# - 从 C# : should I pass StringBuilder or use unsafe code? 调用非托管函数

c++ - Internet Explorer 闪烁的子窗口

c++ - C++ 中相互依赖的类

opengl - OpenGL 中 3D 坐标系的透视问题

c++ - OpenGL 使用 Visual Studio 2010 打开网格 (.m) 文件

math - 无法让我的对象指向鼠标