在保持图像居中的同时放大图像

Zooming in on an image whilst keeping it centered

在下面的应用程序中,您可以单击场景中的任意位置以使 "view" 在该点上居中。

import QtQuick 2.7
import QtQuick.Controls 2.2

ApplicationWindow {
    width: 640
    height: 480
    visible: true

    property real zoom: 1
    property point offset
    property point scenePosToCentreOn

    Item {
        id: sceneView
        anchors.fill: parent

        MouseArea {
            anchors.fill: parent
            onClicked: {
                scenePosToCentreOn = scene.mapFromItem(sceneView, mouse.x, mouse.y)
                offset = Qt.point(scenePosToCentreOn.x - width / 2,
                                  scenePosToCentreOn.y - height / 2);
            }
            onWheel: {
                var zoomFactor = Math.pow(1.4, wheel.angleDelta.y / 120.0);
                var newZoom = Math.min(8.0, Math.max(0.25, zoom * zoomFactor));
                zoom = newZoom;
            }
        }

        Item {
            id: scene
            implicitWidth: backgroundImage.implicitWidth
            implicitHeight: backgroundImage.implicitHeight

            transform: [
                Translate {
                    x: -offset.x
                    y: -offset.y
                },
                Scale {
                    xScale: zoom
                    yScale: zoom
                }
            ]

            Image {
                id: backgroundImage
                source: "http://cdn.akamai.steamstatic.com/steam/apps/393010/ss_29cf93db42617dd08ceb0a0bf0a4b62ad12a1cfc.1920x1080.jpg?t=1459456906"
            }

            Rectangle {
                x: scenePosToCentreOn.x - width / 2
                y: scenePosToCentreOn.y - height / 2
                width: 8
                height: width
                radius: width / 2
                color: "#fff"
            }

            Rectangle {
                anchors.fill: parent
                color: "transparent"
                border.color: "darkorange"
                border.width: 4

                Label {
                    text: "Scene"
                }
            }
        }

        Label {
            text: zoom.toFixed(2)
            font.pixelSize: Qt.application.font.pixelSize * 2
            color: "salmon"
            anchors.right: parent.right
            anchors.bottom: parent.bottom
        }
    }
}

我希望能够放大和缩小选定的点 (scenePosToCentreOn)。它目前在 zoom1 时有效,但对于任何其他 zoom 值,它的原点似乎位于屏幕的左上角。我怀疑我在转换列表中遗漏了一些东西,但我想不出来。

由于计算居中位置和应用刻度的方式,您需要进行补偿。

    Translate {
      x: -offset.x + (((1 / zoom) - 1) * (sceneView.width * .5))
      y: -offset.y + (((1 / zoom) - 1) * (sceneView.height * .5))
    },