[Solved]How to render text in Qt3D ?
-
I use renderText() in the QGLView to render a text, but it does not work.
Any ideas to slove these issues for me ? Great Thanks !!!
The core code:
void Geotech::QGLText::draw(QGLPainter *painter)
{
if (_str.isEmpty()) return;QFontMetrics fm(_font); QRect rect = fm.boundingRect(_str); // text bounding box rect.adjust(0, 0, 1, 1); QImage image(rect.size(), QImage::Format_ARGB32); image.fill(0); // set to transparent // draw the text on an image QPainter p2d(&image); p2d.setFont(_font); p2d.setPen(QColor(_red * 255, _green * 255, _blue * 255, _alpha * 255)); p2d.drawText(0, 0, rect.width(), rect.height(), Qt::AlignCenter, _str); p2d.end(); // convert the object coordinate to screen coordinate GLdouble winx, winy, winz; QMatrix4x4 model = painter->modelViewMatrix().top(); QMatrix4x4 proj = painter->projectionMatrix().top(); QGLUtils::objectToWindowCoord(_x, _y, _z, model.data(), proj.data(), &winx, &winy, &winz); winy -= rect.height()/2.0; // align center of height int x = (int)winx, y = (int)winy; QVector2DArray vertices; vertices.append(x, y + rect.height()); vertices.append(x, y); vertices.append(x + rect.width(), y); vertices.append(x + rect.width(), y + rect.height()); // texture coordinates QVector2DArray texCoord; texCoord.append(0.0f, 0.0f); texCoord.append(0.0f, 1.0f); texCoord.append(1.0f, 1.0f); texCoord.append(1.0f, 0.0f); // map the image to texture QGLTexture2D texture; texture.setImage(image); // get viewport GLint view[4]; glGetIntegerv(GL_VIEWPORT, &view[0]); painter->modelViewMatrix().push(); painter->modelViewMatrix().setToIdentity(); QMatrix4x4 projm; projm.ortho(view[0], view[2], view[3], view[1], 0, 1); painter->projectionMatrix().push(); painter->projectionMatrix() = projm; // move to the actual position from the screen origin painter->modelViewMatrix().translate(0, 0, -winz); // enable blend to make the background transaprecy of the text glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); painter->clearAttributes(); painter->setStandardEffect(QGL::FlatReplaceTexture2D); texture.bind(); painter->setVertexAttribute(QGL::Position, vertices); painter->setVertexAttribute(QGL::TextureCoord0, texCoord); painter->draw(QGL::TriangleFan, 4); painter->setStandardEffect(QGL::FlatColor); glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_BLEND); painter->projectionMatrix().pop(); painter->modelViewMatrix().pop();
}