首页 > 解决方案 > 围绕其中心旋转 MapQuickItem 中的图像

问题描述

我正在使用MapQuickItem带有ImageassourceItem的 a 在 QML 上显示用户的位置Map

的文档MapQuickItem指出:

当显示在屏幕上时,设置的坐标将与包含的项目的左上角对齐。

anchorPoint属性提供了一种将坐标与项目的其他部分对齐的方法,而不仅仅是左上角,方法是设置项目将偏移的像素数。

一种简单的思考方式是注意 anchorPoint项目本身给出的点是在显示时与给定对齐的点coordinate

所以我设置了锚点以匹配图像的中心,如下所示:

anchorPoint.x: img.width/2
anchorPoint.y: img.height/2

这会将箭头的中心放在用户位置的正上方。到现在为止还挺好。

现在,我希望围绕其中心旋转图像以使用该rotation属性显示用户的标题。

Item transformOrigin物业的文件指出:

有九个变换原点可用,如下图所示。默认变换原点是Item.Center.

变换原点

因此,我希望图像围绕其中心旋转,因为这是默认行为。

但不幸的是,现实情况大不相同。围绕图像的左上角应用旋转,使箭头远离用户的位置,如下图所示:

旋转 MapQuickItem


主文件

#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));

    return app.exec();
}

main.qml

import QtQuick 2.0
import QtQuick.Window 2.0
import QtLocation 5.6
import QtPositioning 5.6

Window {
    width: 512
    height: 512
    visible: true

    property variant loc: QtPositioning.coordinate(48.858222, 2.2945)

    Map {
        id: map
        anchors.fill: parent
        plugin: Plugin { name: "osm" }
        center: loc
        zoomLevel: 16

        MapQuickItem {
            id: arrow
            coordinate: loc

            anchorPoint.x: img.width/2
            anchorPoint.y: img.height/2

            sourceItem: Image {
                id: img
                NumberAnimation on rotation { from: 0; to: 360; duration: 2000; loops: Animation.Infinite; }
                source: "arrow.png"
            }
        }
    }
}

箭头.png :https : //pasteboard.co/HYgV7Nf.png

标签: qtqml

解决方案


文档是正确的,问题是如何应用任务的顺序,你正在做的是先旋转图像,然后你只是建立使用左上角作为参考点的 MapQuickItem 源,所以它总是相对于 topLeft 旋转。

解决方案是旋转 MapQuickItem 而不是 sourceItem:

import QtQuick 2.0
import QtQuick.Window 2.0
import QtLocation 5.6
import QtPositioning 5.6

Window {
    width: 512
    height: 512
    visible: true

    property variant loc: QtPositioning.coordinate(48.858222, 2.2945)

    Map {
        id: map
        anchors.fill: parent
        plugin: Plugin { name: "osm" }
        center: loc
        zoomLevel: 16

        MapQuickItem {
            id: arrow
            coordinate: loc
            NumberAnimation on rotation { from: 0; to: 360; duration: 2000; loops: Animation.Infinite; }
            anchorPoint.x: img.width/2
            anchorPoint.y: img.height/2
            sourceItem: Image {
                id: img
                source: "arrow.png"
            }
        }
    }
}

推荐阅读