Qt 文本抗锯齿
1. 通常情况下, 在 paintEvent 中绘制文本时, 不管是否设置抗锯齿选项, 都不会有明显的锯齿, 如下代码所示, Antialiasing/TextAntialiasing 对最终的效果没有显著影响.
QFont ft = painter.font(); ft.setFamily("PingFang SC"); ft.setPixelSize(13); ft.setWeight(QFont::Medium); painter.setFont(ft); painter.setRenderHint(QPainter::Antialiasing, false); painter.setRenderHint(QPainter::TextAntialiasing, false); // painter.setRenderHint(QPainter::Antialiasing, true); // painter.setRenderHint(QPainter::TextAntialiasing, true); painter.drawText(0, 0, 200, 50, Qt::AlignCenter, "Test1234567890");
2. 某些情况下, 我们需要将数据预先绘制到缓存图片上(如多线程构建缓存图片), 再绘制到界面上时, 上述代码就有问题了
if (image.isNull()) { image = QImage(300, 300, QImage::Format_RGBA8888); image.fill(Qt::transparent); QPainter painter(&image); QFont ft = painter.font(); ft.setFamily("PingFang SC"); ft.setPixelSize(13); ft.setWeight(QFont::Medium); painter.setFont(ft); // painter.setRenderHint(QPainter::Antialiasing, false); // painter.setRenderHint(QPainter::TextAntialiasing, false); painter.setRenderHint(QPainter::Antialiasing, true); painter.setRenderHint(QPainter::TextAntialiasing, true); painter.drawText(0, 0, 200, 50, Qt::AlignCenter, "Test1234567890"); } painter.drawImage(0, 0, image);
上述 image 是一个 QImage 对象, 我们启用 Antialiasing/TextAntialiasing, 可以看到文字还是出现了明显的锯齿.
此时我们需要开启字体的抗锯齿选项, 才能避免出现这种现象:
if (image.isNull()) { image = QImage(300, 300, QImage::Format_RGBA8888); image.fill(Qt::transparent); QPainter painter(&image); QFont ft = painter.font(); ft.setFamily("PingFang SC"); ft.setPixelSize(13); ft.setWeight(QFont::Medium); ft.setStyleHint(QFont::AnyStyle, QFont::PreferAntialias); // ft.setStyleStrategy(QFont::PreferAntialias); painter.setFont(ft); painter.drawText(0, 0, 200, 50, Qt::AlignCenter, "Test1234567890"); } painter.drawImage(0, 0, image);
通过设置 ft.setStyleHint(QFont::AnyStyle, QFont::PreferAntialias); 或 ft.setStyleStrategy(QFont::PreferAntialias); 之后, 可以看到, 文本锯齿消失了.
代码养活自己