天天看点

Qt 坐标变换1.坐标变换常用接口2.示例

1.坐标变换常用接口

void translate(qreal dx,qreal dy) 平移
void rotate(qreal angle) 旋转
void scale(qreal sx,qreal sy) 缩放
void save 保存painter当前的状态
void restore() 恢复上一次状态
void resetTransform() 复位所有的坐标变换

2.示例

画五角星

Qt 坐标变换1.坐标变换常用接口2.示例
void Widget::paintEvent(QPaintEvent *event)
{
    //创建QPainter对象,指明父对象,否则不能看见
    QPainter painter(this);

    //先画一条线
    QPen pen;

    //设置线宽
    pen.setWidth(2);

    //设置颜色
    pen.setColor(Qt::red);

    //设置线的样式 实线、虚线
    pen.setStyle(Qt::SolidLine);

    //设置线端点样式
    pen.setCapStyle(Qt::FlatCap);

    pen.setJoinStyle(Qt::BevelJoin);

    //设置画笔
    painter.setPen(pen);

    //半径
    qreal R = 100;
    qreal pi = 3.14159;
    qreal deg = pi*72/180;

    QPoint points[5] = {
        QPoint(R,0),
        QPoint(R*std::cos(deg),-R*std::sin(deg)),
        QPoint(R*std::cos(2*deg),-R*std::sin(2*deg)),
        QPoint(R*std::cos(3*deg),-R*std::sin(3*deg)),
        QPoint(R*std::cos(4*deg),-R*std::sin(4*deg))
    };

    //设置字体
    QFont font;
    font.setPixelSize(12);
    font.setBold(true);
    painter.setFont(font);

    //设置画刷
    QBrush brush;

    //画刷设置颜色
    brush.setColor(Qt::yellow);

    //设置填充样式
    brush.setStyle(Qt::SolidPattern);

    //设置画刷
    painter.setBrush(brush);

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

    //闭合路径,最后一个点与第一个点相连
    painterPath.closeSubpath();

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

    //保持坐标状态
    painter.save();

    //平移
    painter.translate(100,120);

    //画星星
    painter.drawPath(painterPath);

    painter.drawText(0,0,"S1");

    //恢复坐标状态
    painter.restore();

    //平移
    painter.translate(300,120);
    //缩放
    painter.scale(0.8,0.8);
    //顺时针旋转90
    painter.rotate(90);
    painter.drawPath(painterPath);
    painter.drawText(0,0,"S2");

    //复位所有坐标变换
    painter.resetTransform();
    //平移
    painter.translate(500,120);
    //逆时针旋转145
    painter.rotate(-145);

    painter.drawPath(painterPath);
    painter.drawText(0,0,"S3");
}
           

继续阅读