需求:模仿心电图效果
思路:1、实现基本折线图。2、加入定时器,折线图平移
直接上代码:
1、定义波形图视图;
import SwiftUI
struct wavcItemData {
var timeX: CGFloatvar uA: CGFloat
}
struct WaveLineView: View {
@State var dataSouce:[wavcItemData]var timer = Timer.publish(every: 0.01, tolerance: 0.05, on: .main, in: .common).autoconnect()
var body: some View {
GeometryReader { geo in
VStack {Path(){ path in
var beginX: CGFloat = 20
let beginY: CGFloat = 20//开始起点
path.move(to: CGPoint(x: beginX, y: beginY))
dataSouce.forEach { point inpath.addLine(to: CGPoint(x: beginX, y: point.uA))beginX += 1}}
.stroke(Color.orange, lineWidth: 1.0)
.animation(.easeIn, value: true)
Text("Size: (\(geo.size.width), \(geo.size.height))")}
.onReceive(timer) { _ in
let waveValue = Float.randomCGFloatNumber(lower: 0, upper: 100)print("\(waveValue)")
self.dataSouce.insert(wavcItemData.init(timeX: 20, uA: CGFloat(waveValue)), at: 0)}}}}
public extension Float {static func randomCGFloatNumber(lower: Float = 0,upper: Float = 100) -> Float {return Float(arc4random()) / Float(UInt32.max) * (upper - lower) + lower}}
2、直接引用即可; @State var pointsaaa = wavcItemData(timeX: 20, uA: 20)var body: some View {WaveLineView(dataSouce: [pointsaaa])}