swiftui 实现波浪动画

372 阅读1分钟

代码

import SwiftUI

struct WaveView: Shape {
    // 控制波浪的高度
    var amplitude: CGFloat = 50.0
    // 控制波浪的频率
    var frequency: CGFloat = 2.0
    // 控制波浪的相位
    var phase: CGFloat = 0.0
    
    var animatableData: CGFloat {
        get { phase }
        set { phase = newValue }
    }
    
    func path(in rect: CGRect) -> Path {
        let path = UIBezierPath()
        let startPoint = CGPoint(x: 0, y: rect.height / 2)
        path.move(to: startPoint)
        
        for x in stride(from: 0, to: rect.width, by: 1) {
            let y = amplitude * sin((x / rect.width) * frequency * 2 * .pi + phase) + rect.height / 2
            path.addLine(to: CGPoint(x: x, y: y))
        }
        
        // 添加底部的闭合曲线
        path.addLine(to: CGPoint(x: rect.width, y: rect.height))
        path.addLine(to: CGPoint(x: 0, y: rect.height))
        path.close()
        
        return Path(path.cgPath)
    }
}


struct WaveAnimation: View {
    @State private var wavePhase: CGFloat = 0.0
    
    var body: some View {
        
        VStack{
            
            ZStack {
                // 添加波浪视图并设置颜色和透明度
                WaveView(amplitude: 30, frequency: 1.5, phase: wavePhase)
                    .fill(Color.blue)
                    .opacity(0.5)
                    .animation(Animation.linear(duration: 2).repeatForever(autoreverses: false))
                
                WaveView(amplitude: 30, frequency: 1.4, phase: wavePhase)
                    .fill(Color.blue)
                    .opacity(0.5)
                    .animation(Animation.linear(duration: 2).repeatForever(autoreverses: false))
                
            }
        }
        .onAppear {
            // 开始波浪动画
            withAnimation {
                self.wavePhase = .pi * 2
            }
        }
    }
}


struct ContenView_Previews: PreviewProvider {
    static var previews: some View {
        WaveAnimation()
    }
}



image.png