SwiftUI 简单实现气泡上升|雪花飘落效果

气泡演示效果

SwiftUI 实现气泡上升示例效果演示

示例代码

import SwiftUI

struct BubbleAnimationView: View {
    @State private var bubbles: [Bubble] = []
    var body: some View {
    
        ZStack {
            ForEach(bubbles.indices, id: \.self) { index in
                Circle()
                    .frame(width: bubbles[index].size, height: bubbles[index].size)
                    .position(x: bubbles[index].positionX, y: bubbles[index].positionY)
                    .opacity(bubbles[index].opacity)
                    .onAppear {
                        animateBubble(at: index)
                    }
            }
        }
        .edgesIgnoringSafeArea(.all)
        .onAppear(perform: createBubbles)
    }

    func createBubbles() {
        for _ in 0..<100 {
            let size = CGFloat.random(in: 5...15)
            let positionX = CGFloat.random(in: 0...UIScreen.main.bounds.width)
            let positionY = UIScreen.main.bounds.height + size
            let speed = Double.random(in: 4.0...8.0)
            let opacity = Double.random(in: 0.5...1.0)
            let bubble = Bubble(size: size, positionX: positionX, positionY: positionY, speed: speed, opacity: opacity)
            bubbles.append(bubble)
        }
    }
    
    func animateBubble(at index: Int) {
        let delay = Double.random(in: 0...5)
        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
            withAnimation(.easeOut(duration: bubbles[index].speed).repeatForever(autoreverses: false)) {
                bubbles[index].positionY = -100
                bubbles[index].opacity = 0
            }
        }
    }
}

struct Bubble: Identifiable {
    let id = UUID()
    var size: CGFloat
    var positionX: CGFloat
    var positionY: CGFloat
    var speed: Double
    var opacity: Double
}

 


#Preview {
    BubbleAnimationView()
}

示例代码下载

SwiftUI 简单实现气泡上升|雪花飘落效果

SwiftUI 气泡上升示例代码

资源价格 ¥0.00 销售数量 0 更新时间 2024-11-14
已经登录?刷新

  本文自 https://www.codeun.com 发布,相应代码均自主编写并严格审阅和测试,完整代码中包含丰富的学习笔记和使用方式、实用技巧。
  · 如若转载,请注明出处:https://www.codeun.com/archives/1394.html ·

(0)
上一篇 2024-11-14 下午2:35
下一篇 2024-11-15 下午3:36

相关推荐

发表回复

登录后才能评论