我想使用QPainter
绘制文字,我想首先使用QPainterPath
(因为最终我想以各种方式旋转文本)。但是,我发现QPainterPath
生成的文字比QPainter
生成的文字更加丑陋。
以下代码:
void MyWidget::paintEvent(QPaintEvent* /*event*/) {
QFont font;
font.setStyleHint(QFont::Times, QFont::PreferAntialias);
font.setPointSize(30);
QPainter painter;
painter.begin(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.setBrush(Qt::black);
painter.setFont(font);
painter.drawText(10, 40, "Hello World");
QPainterPath textPath;
textPath.addText(10, 100, font, "Hello world");
painter.drawPath(textPath);
painter.end();
}
产生以下结果:
前者显然更清洁,更好,特别是在较小的字体中。我该怎么做才能从QPainterPath
获得相同的结果?
我在Windows 7计算机上使用Qt 5.0生成上述结果。
答案 0 :(得分:5)
根据Qt文档向QPainterPath添加文本: -
将给定文本作为一组创建的已关闭子路径添加到此路径 从提供的字体。
所以这里有转换,这就是它看起来不一样的原因。如果需要旋转文本,可以尝试在渲染之前旋转QPainter,然后再恢复它。或者,如果您可以使用QGraphicsView和QGraphicsDisplay而不是仅仅渲染到窗口小部件,那么可以使用QGraphicsTextItem类。
但总的来说,它是转换为一组封闭的子路径,负责不同的文本质量输出。
答案 1 :(得分:4)
这两种字体看起来并不相同,因为您正在为QPainterPath文本添加额外的轮廓。 以下代码应该会给出好的结果:
QFont font;
font.setStyleHint(QFont::Times, QFont::PreferAntialias);
font.setPointSize(30);
QPainter painter;
painter.begin(this);
painter.setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing);
painter.setFont(font);
// painter text color is modified by setPen()
painter.setPen(Qt::white);
painter.drawText(10, 40, "Hello World 1");
QPainterPath textPath;
textPath.addText(10, 100, font, "Hello World 2");
// painter path text color is modified by setBrush()
painter.setBrush(Qt::white);
// setPen(Qt::white) add extra white contour on text path (what you did)
painter.setPen(Qt::white);
painter.drawPath(textPath);
QPainterPath textPath2;
textPath2.addText(10, 160, font, "Hello World 3");
// painter path text color is modified by setBrush
painter.setBrush(Qt::white);
// setPen(Qt::NoPen) avoid extra contours for QPainter Path
painter.setPen(Qt::NoPen);
painter.drawPath(textPath2);
painter.end();
我承认QPainterPath文本“Hello World 3”有点丑陋,QPainterText“Hello World 1”,但结果仍然比“Hello World 2”更好