//QString tempImagePath="./test.png";
//图片上的字符串,例如 HELLO
QString imageText="H E L L O";
QFont font;
//设置显示字体的大小
font.setPixelSize(25);
QFontMetrics fm(font);
int charWidth = fm.width(imageText);
charWidth = fm.boundingRect(imageText).width();
//指定图片大小为字体的大小
QSize size(charWidth+8, 25);
//以ARGB32格式构造一个QImage
QImage image(size, QImage::Format_ARGB32);
//填充图片背景,R红色,G绿色,B蓝色,A透明度
image.fill(qRgba(0, 0, 255, 255));
//为这个QImage构造一个QPainter
QPainter painter(&image);
//设置画刷的组合模式CompositionMode_SourceOut这个模式为目标图像在上。
//改变组合模式和上面的填充方式可以画出透明的图片。
painter.setCompositionMode(QPainter::CompositionMode_SourceOut);
//改变画笔和字体
QPen pen = painter.pen();
pen.setColor( QColor(255, 255, 255));
painter.setPen(pen);
painter.setFont(font);
//将Hello写在Image的中心
painter.drawText(image.rect(), Qt::AlignCenter, imageText);
//int ret = image.save(tempImagePath, "PNG", 100);
//qDebug() << "ret = " << ret;
QLabel *pLabel = new QLabel(this);
pLabel->setFixedSize(size);
pLabel->setPixmap(QPixmap::fromImage(image));
QT 在图上写字
最新推荐文章于 2023-04-23 11:50:56 发布