在裁剪为矩形大小时在 QML 中缩放图像

Scaling an image in QML while cropping to a rectangle's size

我有一个固定大小的黄色 QML 矩形,我正在其中缩放图像。

发生这种情况时,我的图像最终会变得比我的黄色矩形大(很明显)。但是当发生这种情况时,我希望我的图像只在矩形内绘制,而不是延伸到它上面

这是我的代码:

import QtQuick 2.1
import QtQuick.Controls 1.0

Rectangle{
    width: 1500
    height: 1100
    color: "red"
    
    Rectangle {
        width: 900
        height: 500
        color: "yellow"
    
        Component.onCompleted: init()
        
        Image {
            id: imagenCentro
            width: 800
            height: 400
            fillMode: Image.PreserveAspectCrop
            source: "http://www.bizh2o.com/wp-content/uploads/2015/02/shopping.jpg"
            smooth: true
            z: parent.z+1
            opacity: 0.7
        }

        NumberAnimation {
            id: animacion
            target: imagenCentro
            property: "scale"
            to: 1.5
            easing.type: Easing.InOutQuad
        }

        function init(){
            imagenCentro.scale = 1
            animacion.duration = 5000
            animacion.start()
        }
           
    }

}

谢谢。

在黄色矩形上将 clip 设置为 true

import QtQuick 2.1
import QtQuick.Controls 1.0

Rectangle {
    width: 1500
    height: 1100
    color: "red"

    Rectangle {
        width: 900
        height: 500
        color: "yellow"
        clip: true

        Component.onCompleted: init()

        Image {
            id: imagenCentro
            width: 800
            height: 400
            fillMode: Image.PreserveAspectCrop
            source: "http://www.bizh2o.com/wp-content/uploads/2015/02/shopping.jpg"
            smooth: true
            z: parent.z + 1
            opacity: 0.7
        }

        NumberAnimation {
            id: animacion
            target: imagenCentro
            property: "scale"
            to: 1.5
            easing.type: Easing.InOutQuad
        }

        function init() {
            imagenCentro.scale = 1
            animacion.duration = 5000
            animacion.start()
        }
    }
}

注意 clip does come with performance penalties:

Clipping is disabled by default, and should only be enabled when required.

Clipping is a visual effect, NOT an optimization. It increases (rather than reduces) complexity for the renderer. If clipping is enabled, an item will clip its own painting, as well as the painting of its children, to its bounding rectangle. This stops the renderer from being able to reorder the drawing order of elements freely, resulting in a sub-optimal best-case scene graph traversal.

Clipping inside a delegate is especially bad and should be avoided at all costs.