QT5笔记:33. 坐标系统和坐标变换

image
例子:重写widget的painterEvent

MainWindow.cpp

void Widget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::RenderHint::HighQualityAntialiasing);

    QPen pen;
    pen.setColor(QColor(170, 170, 90));
    pen.setWidth(5);
    pen.setStyle(Qt::SolidLine);
    painter.setPen(pen);

    QBrush brush;
    brush.setColor(QColor(120, 180, 200));
    brush.setStyle(Qt::BrushStyle::SolidPattern);
    painter.setBrush(brush);

    qreal radio = 100;
    qreal deg = 3.1415926535797 / 180 * 72;

    QPoint points[5] = {//按照 1 3 5 2 4 的顺序就可以完成绘制,简单方法
        QPoint(radio, 0),
        QPoint(radio * qCos(deg), -radio * qSin(deg)),
        QPoint(radio * qCos(deg * 2), -radio * qSin(deg * 2)),
        QPoint(radio * qCos(deg * 3), -radio * qSin(deg * 3)),
        QPoint(radio * qCos(deg * 4), -radio * qSin(deg * 4))
    };

    QPainterPath path;
    path.moveTo(points[3]);
    path.lineTo(points[1]);
    path.lineTo(points[4]);
    path.lineTo(points[2]);
    path.lineTo(points[0]);
    path.closeSubpath();

    QFont font;
    font.setPointSize(15);
    font.setFamily("MiSans");
    painter.setFont(font);

    path.addText(points[0], font, "0");
    path.addText(points[1], font, "1");
    path.addText(points[2], font, "2");
    path.addText(points[3], font, "3");
    path.addText(points[4], font, "4");

    painter.save();//保存painter矩阵状态:旋转、缩放、平移
    painter.translate(200, 200);//平移原点
    painter.drawText(0, 0, "S1");
    painter.drawPath(path);

    painter.restore();

    painter.translate(200 + 200, 200);//平移原点
    painter.rotate(90);//角度制,旋转
    painter.scale(0.75, 0.75);
    painter.drawText(0, 0, "S2");
    painter.drawPath(path);

    painter.resetTransform();//恢复到未做旋转、缩放、平移的状态

    painter.translate(200 + 200 + 200, 200);//平移原点
    painter.scale(0.75, 0.75);
    painter.drawText(0, 0, "S3");
    painter.drawPath(path);
}

界面:
image

posted @ 2023-03-16 13:44  echo_lovely  阅读(143)  评论(0编辑  收藏  举报