如何围绕圆圈绘制文字?

时间:2012-01-01 17:04:18

标签: c++ qt

使用QT,我如何获取用户提供的输入(文本)并以“跟随”圆形路径的方式绘制字体?

1 个答案:

答案 0 :(得分:2)

我对QT一无所知,但如果我理解你的问题,我会通过简单的谷歌搜索找到解决方案。代码如下,这里是源链接:

http://developer.qt.nokia.com/faq/answer/how_do_i_make_text_follow_the_line_curve_and_angle_of_the_qpainterpath

#include <QtGui>
#include <cmath>

class Widget : public QWidget
{
public:
    Widget ()
        : QWidget() { }
private:
    void paintEvent ( QPaintEvent *)
    {
        QString hw("hello world");
        int drawWidth = width() / 100;
        QPainter painter(this);
        QPen pen = painter.pen();
        pen.setWidth(drawWidth);
        pen.setColor(Qt::darkGreen);
        painter.setPen(pen);

        QPainterPath path(QPointF(0.0, 0.0));

        QPointF c1(width()*0.2,height()*0.8);
        QPointF c2(width()*0.8,height()*0.2);

        path.cubicTo(c1,c2,QPointF(width(),height()));

        //draw the bezier curve
        painter.drawPath(path);

        //Make the painter ready to draw chars
        QFont font = painter.font();
        font.setPixelSize(drawWidth*2);
        painter.setFont(font);
        pen.setColor(Qt::red);
        painter.setPen(pen);

        qreal percentIncrease = (qreal) 1/(hw.size()+1);
        qreal percent = 0;

        for ( int i = 0; i < hw.size(); i++ ) {
            percent += percentIncrease;

            QPointF point = path.pointAtPercent(percent);
            qreal angle = path.angleAtPercent(percent);

            qreal rad =qreal(0.017453292519943295769)*angle; // PI/180

            // From the documentation:
            /**
              QTransform transforms a point in the plane to another point using the following formulas:
              x' = m11*x + m21*y + dx
              y' = m22*y + m12*x + dy
            **/
            // So the idea is to find the "new position of the character
            // After we apply the world rotation.
            // Then translate the painter back to the original position.
            qreal sina = std::sin(rad);
            qreal cosa = std::cos(rad);

            // Finding the delta for the penwidth
            // Don't divide by 2 because some space would be nice
            qreal deltaPenX = cosa * pen.width();
            qreal deltaPenY = sina * pen.width();
            // Finding new posision after rotation
            qreal newX = (cosa * point.x()) - (sina * point.y());
            qreal newY = (cosa * point.y()) + (sina * point.x());

            // Getting the delta distance
            qreal deltaX = newX - point.x();
            qreal deltaY = newY - point.y();
            // Applying the rotation with the translation.
            QTransform tran(cosa,sina,-sina,cosa,-deltaX + deltaPenX,-deltaY - deltaPenY);

            painter.setWorldTransform(tran);
            painter.drawText(point,QString(hw[i]));
        }
    }

};

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    Widget widget;
    widget.show();
    return app.exec();
}