Last active
April 11, 2022 12:35
-
-
Save nkint/9089157 to your computer and use it in GitHub Desktop.
opengl in qt: render string to QImage to texture
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void displayText(const QString &text, const QColor &backgroundColor, const QColor &textColor, const Vec3D &pos) | |
{ | |
// some magic number (margin, spacing, font size, etc..) | |
int fontSize = 15; | |
int text_width=text.size()*(fontSize/1.5)+5, text_height=fontSize+20; | |
// create the QImage and draw txt into it | |
QImage textimg(text_width, text_height, QImage::Format_RGB888); | |
{ | |
QPainter painter(&textimg); | |
painter.fillRect(0, 0, text_width, text_height, backgroundColor); | |
painter.setBrush(textColor); | |
painter.setPen(textColor); | |
painter.setFont(QFont("Sans", fontSize)); | |
painter.drawText(5, 20, text); | |
} | |
// // very stupid debug. warning: do not use in animation loop | |
// QWidget *w = new QWidget(); | |
// QLabel *l = new QLabel(); | |
// l->setPixmap(QPixmap::fromImage(textimg)); | |
// l->setParent(w); | |
// w->show(); | |
// std::cout << "test image!" << std::endl; | |
// now the texture | |
glEnable(GL_TEXTURE_2D); | |
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); | |
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); | |
glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE); | |
glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE); | |
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); | |
glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0); | |
glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); | |
glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); | |
glPixelStorei(GL_UNPACK_SKIP_IMAGES, 0); | |
glPixelStorei(GL_UNPACK_ALIGNMENT, 4); | |
glTexImage2D(GL_TEXTURE_2D, 0, | |
GL_RGB8, text_width, text_height, 0, | |
GL_RGB, GL_UNSIGNED_BYTE, textimg.constBits()); | |
// old style GL drawing, very stupid. use gl vertex array instead | |
// just for reduce the gist! | |
glPushMatrix(); | |
glTranslatef(pos.x, pos.y, pos.z); | |
glBegin(GL_QUADS); | |
glTexCoord2f(1, 0); glVertex3f(0, 0, 0); | |
glTexCoord2f(0, 0); glVertex3f(text_width, 0, 0); | |
glTexCoord2f(0, 1); glVertex3f(text_width, text_height, 0); | |
glTexCoord2f(1, 1); glVertex3f(0, text_height, 0); | |
glEnd(); | |
glPopMatrix(); | |
glDisable(GL_TEXTURE_2D); | |
glFlush(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment