高效地围绕 QPainterPath 绘制文本

Draw text around QPainterPath efficiently

以下代码在 QPainterPath 周围绘制文本:

QString text = "Short text";
QPainterPath rawPath;
// fill path ...

while (...)
{
    double percent = ...;
    double angle = rawPath.angleAtPercent(percent);
    QPointF point = rawPath.pointAtPercent(percent);

    m_painter.save();

    m_painter.translate(point);
    m_painter.rotate(-angle);

    // Version 1:
    //m_painter.drawText(0, 0, text.at(currentChar));

    // Version 2:
    QPainterPath p2;
    p2.addText(0, 0, font, text.at(currentChar));
    m_painter.drawPath(p2);

    m_painter.restore();
}

图形结果符合预期,但版本 1 和版本 2 的性能都很差。瓶颈分别是 QPainter::drawText()QPainterPath::addText() 方法。有没有更有效的方法来围绕路径绘制文本?

此致,

没有按照路径绘制文本的内置方法。

但是,如果 QPainter 不够有效,您可以通过使用文本构建新路径并在循环后绘制来获得一些性能(您不会使用 QPainter::save()QPainter::restore() 在循环中):

void paintEvent(QPaintEvent* event)
    {
        QString text = "Short text";
        text = text.repeated(1000); // Check with a very long text
        QPainterPath rawPath;
        rawPath.addEllipse(QRect(0, 0, 200, 200));

        QPainterPath path;

        double const step = 1.0 / double(text.length());
        double percent = 0.0;
        for(QChar const& c: text)
        {
            double angle = rawPath.angleAtPercent(percent);
            QPointF point = rawPath.pointAtPercent(percent);

            QTransform mat;
            mat.rotate(-angle);
            QPainterPath p2;
            p2.addText(0, 0, font(), c);
            p2 = mat.map(p2);
            path.addPath(p2.translated(point));
            percent += step;
        }

        QPainter painter(this);
        painter.drawPath(path.translated(100, 100));
    }