看本文章的人我相信都不需要我介绍Qt和OpenGL了。文字的绘制一直都是3D开发的一个难题,本文将介绍一种非常简单,效率也还可以的方法来渲染文字到OpenGL。
先讲原理,Qt的QPainter拥有将内容绘制到QImage设备的能力,也就是直接会知道文字,因此,可以通过QPainter的drawText方法将文本绘制到一张Image,再创建成纹理,渲染到OpenGL目标中。
先给一个效果图:
从文字创建纹理的方法如下:
QOpenGLTexture *GLWindow::genTexture(int width, int height, const QString &text, int textPixelSize, const QColor &textColor)
{
QOpenGLTexture *texture = new QOpenGLTexture(QOpenGLTexture::Target2D);
QImage img(width, height, QImage::Format_ARGB32_Premultiplied);//img是图片,模式为QImage::Format_ARGB32_Premultiplied是因为按官方的说法,这个模式快。
img.fill(QColor(0, 0, 0, 0)); //填充为透明
QPainter painter;
QFont font;
painter.begin(&img);
font.setPixelSize(textPixelSize);
painter.setFont(font);
QPen pen;
pen.setColor(textColor);
painter.setPen(pen);
QTextOption option(Qt::AlignLeft | Qt::AlignTop);//这里使文字绘制时自动换行
option.setWrapMode(QTextOption::WordWrap);
QRectF rect(0, 0, width, height);
painter.drawText(rect, text, option);//绘制到图片
painter.end();
//创建为纹理。
texture->setData(img);
// texture->setMipLevelRange(0, mipLevelMax);//off mipmap 没必要,开了影响效果
texture->setMinificationFilter(QOpenGLTexture::Linear);//线性滤波方式,文字看上去柔和
texture->setMagnificationFilter(QOpenGLTexture::Linear);
texture->setWrapMode(QOpenGLTexture::Repeat);
return texture;
}
最终将纹理绑定到渲染目标即可。
demo尝试了一个60fps的渲染,且每一帧都会重新创建一个纹理,效率上还是可以的。
完整demo地址:https://github.com/giarld/MyQtDemo/tree/master/opengl_new/textTexture
源代码及文章所有权归作者所有,转载请注明出处。