admaDIC App Development & IT Solutions

SwiftUI MeshGradient

by Annett Schwarze | 2025-04-04

SwiftUI MeshGradients offer complex gradients aligned with a grid.

        
import SwiftUI

@available(iOS 18.0, *)
struct SampleMeshGradientView: View {
    @State private var hue: CGFloat = 0.0
    @State private var points: [SIMD2] = [
        [0.0, 0.0], [0.5, 0.0], [1.0, 0.0],
        [0.0, 0.5], [0.9, 0.3], [1.0, 0.5],
        [0.0, 1.0], [0.5, 1.0], [1.0, 1.0]
    ]
    @State private var colors = Array(repeating: Color.white, count: 9)
    @State private var timer: Timer?

    var body: some View {
        VStack {
            HStack {
                Slider(value: $hue, onEditingChanged: { flag in
                    withAnimation {
                        makeColors()
                    } completion: {
                    }
                })
            }
            MeshGradient(
                width: 3,
                height: 3,
                points: points,
                colors: colors
            )
        }
        .padding()
        .task {
            makeColors()
            timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { t in
                withAnimation(Animation.linear(duration: 0.5)) {
                    let step = 0.2
                    hue = hue + step > 1.0 ? 0.0 : hue + step
                    makeColors()
               } completion: {
               }
           })
        }
    }

    private func makeColors() {
        var colors: [Color] = []
        for row in 0..<3 {
            for col in 0..<3 {
                colors.append(color(row: row, col: col))
            }
        }
        self.colors = colors
    }

    private func color(row: Int, col: Int) -> Color {
        let delta = CGFloat.random(in: -0.1 ... 0.1)
        let h = max(0.0, min(1.0, (hue + delta)))
        return Color(hue: h, saturation: 1.0, brightness: 1.0).opacity(0.5)
    }
}

@available(iOS 18.0, *)
#Preview {
    SampleMeshGradientView()
}
MeshGradients

 

www.admadic.de | webmaster@admadic.de | Legal Notice and Trademarks | Privacy
© 2005-2007 - admaDIC | All Rights Reserved
All other trademarks and/or registered trademarks are the property of their respective owners
Last Change: Fri Apr 4 09:06:16 2025 GMT