You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI如何创建彩色方块矩阵网格 实现96x96色块动态更新需求

SwiftUI 高性能96x96动态彩色矩阵实现方案

核心采用 Canvas 即时绘制 方案,避免创建大量独立View,完全满足每秒全量更新的性能要求。

实现代码

import SwiftUI

struct DynamicColorMatrix: View {
    let rows: Int
    let columns: Int
    // 外部传入的颜色矩阵,按行优先排序:第i行第j列对应索引 i*columns + j
    @Binding var colorMatrix: [Color]
    
    var body: some View {
        Canvas { context, size in
            // 计算单个色块尺寸
            let blockWidth = size.width / CGFloat(columns)
            let blockHeight = size.height / CGFloat(rows)
            
            // 遍历所有色块完成绘制
            for row in 0..<rows {
                for column in 0..<columns {
                    let index = row * columns + column
                    guard index < colorMatrix.count else { continue }
                    // 计算当前色块坐标
                    let rect = CGRect(
                        x: CGFloat(column) * blockWidth,
                        y: CGFloat(row) * blockHeight,
                        width: blockWidth,
                        height: blockHeight
                    )
                    // 填充对应颜色
                    context.fill(Path(rect), with: .color(colorMatrix[index]))
                }
            }
        }
    }
}

使用示例

包含每秒动态更新矩阵逻辑,可直接替换为你的业务计算逻辑:

struct MatrixDemoView: View {
    // 96x96矩阵总计9216个色块
    @State private var colorMatrix: [Color] = Array(repeating: .black, count: 96*96)
    // 模拟每秒更新数据的计时器
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    
    var body: some View {
        DynamicColorMatrix(
            rows: 96,
            columns: 96,
            colorMatrix: $colorMatrix
        )
        // 自定义矩阵展示尺寸
        .frame(width: 300, height: 300)
        .onReceive(timer) { _ in
            // 每秒全量更新色块颜色,替换为你自身的矩阵数值转颜色逻辑即可
            for i in 0..<colorMatrix.count {
                // 示例为随机颜色,实际使用时替换为TermoColor映射后的结果
                colorMatrix[i] = Color(
                    red: Double.random(in: 0...1),
                    green: Double.random(in: 0...1),
                    blue: Double.random(in: 0...1)
                )
            }
        }
    }
}

方案优势

  • 性能极强:Canvas属于轻量级绘制方案,全程仅需1个绘制载体,没有LazyVGrid近千个View的布局、渲染开销,96x96量级每秒全量更新无卡顿,内存占用极低
  • 适配成本低:颜色矩阵的更新逻辑和你之前UIKit实现的图层更新逻辑完全对齐,可直接复用现有矩阵数值转颜色的业务代码
  • 维护简单:不需要维护大量图层或View实例,所有绘制逻辑集中管理

内容的提问来源于stack exchange,提问作者Marino Pereša

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 06:36:03