# 简单变换

变换操作对象的几何形状, QML项通常可以被平移、旋转和缩放。 这些操作有一种简单的形式和一种更高级的方法。

先从简单的转换开始。 以下面的场景为起点阅读。

一个简单的变换是通过改变x,y位置来完成的; 旋转是使用rotation属性完成的, 该值用度数(0到360)表示; 缩放使用scale属性完成,值<1表示元素被缩小,而>1表示元素被放大。 旋转和缩放不会改变项的几何形状:x,ywidth/height 没有改变; 只有绘画指令被变换。

在展示示例之前,介绍一个小帮手:ClickableImage元素。 ClickableImage只是一个带有鼠标区域的图像。 用这说明一个有用的经验法则——如果已经复制了一段代码3次,请将其提取到一个组件中。

// ClickableImage.qml
// Simple image which can be clicked

import QtQuick

Image {
    id: root
    signal clicked

    MouseArea {
        anchors.fill: parent
        onClicked: root.clicked()
    }
}

使用可点击的图像来呈现三个对象(方框、圆形、三角形)。 每个对象在单击时都会执行一个简单的转换,单击背景将重置场景。

// TransformationExample.qml

import QtQuick

Item {
    // set width based on given background
    width: bg.width
    height: bg.height

    Image { // nice background image
        id: bg
        source: "assets/background.png"
    }

    MouseArea {
        id: backgroundClicker
        // needs to be before the images as order matters
        // otherwise this mousearea would be before the other elements
        // and consume the mouse events
        anchors.fill: parent
        onClicked: {
            // reset our little scene
            circle.x = 84
            box.rotation = 0
            triangle.rotation = 0
            triangle.scale = 1.0
        }
    }

    ClickableImage {
        id: circle
        x: 84; y: 68
        source: "assets/circle_blue.png"
        antialiasing: true
        onClicked: {
            // increase the x-position on click
            x += 20
        }
    }

    ClickableImage {
        id: box
        x: 164; y: 68
        source: "assets/box_green.png"
        antialiasing: true
        onClicked: {
            // increase the rotation on click
            rotation += 15
        }
    }

    ClickableImage {
        id: triangle
        x: 248; y: 68
        source: "assets/triangle_red.png"
        antialiasing: true
        onClicked: {
            // several transformations
            rotation += 15
            scale += 0.05
        }
    }
    
    // ...

每次单击圆圈时,它都会增加其x位置;每次单击时方框时,它会旋转;在每次单击三角形时,它会旋转并放大图像,以演示组合变换。 对于缩放和旋转操作,我们设置 antialiasing: true 以启用抗锯齿,出于性能原因可将其关闭(与剪辑属性 clip 相同)。 在工作中,当在图形中看到一些光栅化的边缘时,可能应该打开平滑设置。

提示

为了在缩放图像时获得更好的视觉质量,建议缩小而不是放大。 使用较大的缩放因子放大图像将导致缩放伪影(图像模糊)。 在缩放图像时,您应该考虑使用smooth: true以牺牲性能为代价启用更高图像质量的过滤器。

MouseArea覆盖整个背景并重置原始背景的值。

提示

代码中较早出现的元素具有较低的堆叠顺序(称为z顺序)。 如果在circle上单击足够长的时间,将看到它在box下方移动。 z顺序也可以通过Item的z属性操作。

这是因为box出现在代码的后面。 这同样适用于鼠标区域。 代码后面的鼠标区域将覆盖代码前面的鼠标区域,从而后面的鼠标区域抓取到鼠标事件。

请记住:文档中元素的顺序很重要

最后更新: 11/28/2021, 3:42:31 PM