SwiftUI 动画之绘制仿心跳曲线动画 (教程含源码)

实战需求

SwiftUI 动画之绘制仿心跳曲线动画 (教程含源码)

本文价值与收获

看完本文后,您将能够作出下面的界面

SwiftUI 动画之绘制仿心跳曲线动画 (教程含源码)_第1张图片
绘制仿心跳曲线动画
绘制仿心跳曲线动画

看完本文您将掌握的技能

  • SwiftUI Path绘制心跳曲线
struct HeartBeat : Shape {
    func path(in rect: CGRect) -> Path {
        var path = Path()
        path.move(to: CGPoint(x: rect.minX, y: rect.midY))
        path.addLine(to: CGPoint(x: rect.midX-20, y: rect.midY))
        path.addLine(to: CGPoint(x: rect.midX, y: (rect.midY+rect.maxY)/2))
        path.addLine(to: CGPoint(x: rect.midX+10, y: rect.midY))
        path.addLine(to: CGPoint(x: rect.midX+20, y: (rect.midY/2)))
        path.addLine(to: CGPoint(x: rect.midX+40, y: rect.midY))
        path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
        return path
    }
}
  • SwiftUI Timer和onReceive组合实现定时器
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

@State var trimValue1 : CGFloat = 0
@State var trimValue2 : CGFloat = 0

.onReceive(timer, perform: { _ in
            if trimValue2 == 0 {
                trimValue2 = 1
            }
            else if trimValue1 == 0 {
                trimValue1 = 1
            } else {
                trimValue2 = 0
                trimValue1 = 0
            }
        })

你可能感兴趣的:(SwiftUI 动画之绘制仿心跳曲线动画 (教程含源码))