QML/QtQuick2 将项目锚定到缩放图像上的静态位置

QML/QtQuick2 Anchor Item to static location on a scaled image

我正在尝试做的是将项目锚定在图像上的特定位置。图像需要使用 Image.PreserveAspectFit 作为填充模式。我遇到的问题是图像的 height/width/paintedWidth/paintedHeight 是针对整个图像 "canvas" (我不确定它实际上叫什么),而不是图像本身的绘制部分。所以我无法锚定到实际图像。

有关我尝试使用锚点(红色矩形)和子矩形以及 x,y 坐标(绿色矩形)的示例,请参见下面的代码。

import QtQuick 2.3
import QtQuick.Window 2.2

Window {
    visible: true

height: 400
width: 400

Image {
    id: image
    anchors.fill: parent
    fillMode: Image.PreserveAspectFit
    source: "image.jpg"

    Rectangle {
        id: bottomRight
        width: 40
        height: 40
        color: "green"
        x: parent.width * 0.75
        y: parent.height * 0.75
    }
}

Rectangle {
    id: topLeft
    width: 40
    height: 40
    color: "red"

    anchors.top: image.top
    anchors.left: image.left
    anchors.topMargin: image.height * 0.25
    anchors.leftMargin: image.width * 0.25
    }
}

当您更改 window 的大小时,矩形的位置与图像上的位置不同。我会 post 一些屏幕截图,但我还没有足够的声誉!

我使用调试器浏览了小部件树,但我似乎找不到任何提供缩放信息的属性,我可以使用它来计算矩形的位置。

更新 我使用以下函数来计算边距,因为我可能会使用很多这样的叠加层。

function horMargin(val)
{
    return ((image.width - image.paintedWidth)/2  + image.paintedWidth * val)
}

function verMargin(val)
{
    return ((image.height - image.paintedHeight)/2 + image.paintedHeight * val)
}

您是否尝试使用paintedWidthpaintedHeight? :)

这将为您提供一个填充绘制图像的矩形:

import QtQuick 2.3
import QtQuick.Window 2.2

Window {
    visible: true

    height: 400
    width: 400

    Image {
        id: image
        anchors.fill: parent
        fillMode: Image.PreserveAspectFit
        source: "image.jpg"
    }

    Rectangle {
        x: (image.width - image.paintedWidth) / 2
        y: (image.height - image.paintedHeight) / 2
        width: image.paintedWidth
        height: image.paintedHeight
        color: "transparent"
        border.color: "darkorange"
        border.width: 2
    }
}

从那里,您可以计算出如何应用您需要的边距。