QML BorderImage的使用

49 阅读2分钟

BorderImage 是 QML 中一个特殊的图像元素,它使用 九宫格缩放(9-patch scaling)  技术,非常适合创建可伸缩的界面元素而不失真。 QT官方介绍传送门:BorderImage QML Type | Qt Quick 5.15.19

🌟 核心概念

BorderImage 将图片划分为 9 个区域:

┌───┬───┬───┐
│ 1 │ 2 │ 3 │
├───┼───┼───┤
│ 4 │ 5 │ 6 │
├───┼───┼───┤
│ 7 │ 8 │ 9 │
└───┴───┴───┘
  • 角区域(1,3,7,9) :保持原始尺寸,不缩放
  • 边区域(2,8) :水平方向缩放
  • 边区域(4,6) :垂直方向缩放
  • 中心区域(5) :水平和垂直都缩放

📝 基本属性

属性类型说明
borderrectangle定义九宫格的边界宽度
sourceurl图像源文件路径
horizontalTileModeenum水平平铺模式
verticalTileModeenum垂直平铺模式

🎯 平铺模式

模式说明
BorderImage.Stretch拉伸填充(默认)
BorderImage.Repeat重复平铺
BorderImage.Round智能平铺,调整尺寸适配

💻 代码示例

基础用法:创建可伸缩按钮

import QtQuick 2.15
import QtQuick.Controls 2.15

ApplicationWindow {
    width: 400
    height: 300
    visible: true

    BorderImage {
        id: scalableButton
        width: 200
        height: 60
        anchors.centerIn: parent
        
        source: "images/button_bg.png"
        
        // 关键:定义九宫格边界
        // left: 10, top: 10, right: 10, bottom: 10
        border { 
            left: 10; top: 10; 
            right: 10; bottom: 10 
        }

        // 添加按钮文本
        Text {
            text: "点击我"
            anchors.centerIn: parent
            color: "white"
            font.pixelSize: 16
        }

        MouseArea {
            anchors.fill: parent
            onClicked: console.log("按钮被点击!")
        }
    }
}

对话框背景示例

BorderImage {
    width: 300
    height: 200
    source: "images/dialog_bg.png"
    
    border {
        left: 20; top: 20
        right: 20; bottom: 20
    }
    
    // 内容区域
    Column {
        anchors {
            fill: parent
            margins: 30  // 留出边框区域
        }
        spacing: 10
        
        Text {
            text: "这是一个对话框"
            font.bold: true
            font.pixelSize: 18
        }
        
        Text {
            text: "这是对话框的内容区域..."
            font.pixelSize: 14
        }
    }
}

进度条背景

BorderImage {
    id: progressBarBg
    width: 250
    height: 30
    source: "images/progress_bg.png"
    
    border {
        left: 5; top: 5
        right: 5; bottom: 5
    }
    
    // 进度填充
    BorderImage {
        id: progressFill
        width: parent.width * 0.7  // 70% 进度
        height: parent.height
        source: "images/progress_fill.png"
        
        border {
            left: 3; top: 3
            right: 3; bottom: 3
        }
    }
}

⚠️ 注意事项

  1. 边界值设置border 的值应该基于图片的实际特征来设置
  2. 图片资源:确保九宫格图片的角区域包含重要视觉元素
  3. 性能考虑:复杂的 BorderImage 可能会影响渲染性能
  4. 资源路径:注意图片路径的正确性,可以使用 qrc:/ 前缀访问资源文件

🆚 BorderImage vs Image

特性BorderImageImage
缩放方式九宫格智能缩放整体缩放
适用场景按钮、边框、对话框照片、图标
失真问题边角不失真整体拉伸可能失真
复杂度较高较低

BorderImage 特别适合创建需要保持边角细节的可伸缩UI组件,是现代UI设计中不可或缺的工具。