forked from dmrschmidt/DSWaveformImage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WaveformLiveCanvas.swift
76 lines (66 loc) · 2.4 KB
/
WaveformLiveCanvas.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import SwiftUI
import DSWaveformImage
@available(iOS 15.0, macOS 12.0, *)
public struct WaveformLiveCanvas: View {
public static let defaultConfiguration = Waveform.Configuration(damping: .init(percentage: 0.125, sides: .both))
public let samples: [Float]
public let configuration: Waveform.Configuration
public let renderer: WaveformRenderer
public let shouldDrawSilencePadding: Bool
@StateObject private var waveformDrawer: WaveformImageDrawer
public init(
samples: [Float],
configuration: Waveform.Configuration = defaultConfiguration,
renderer: WaveformRenderer = LinearWaveformRenderer(),
shouldDrawSilencePadding: Bool = false
) {
let drawer = WaveformImageDrawer()
self.samples = samples
self.configuration = configuration
self.renderer = renderer
self.shouldDrawSilencePadding = shouldDrawSilencePadding
drawer.shouldDrawSilencePadding = shouldDrawSilencePadding
_waveformDrawer = StateObject(wrappedValue: drawer)
}
public var body: some View {
Canvas(rendersAsynchronously: true) { context, size in
context.withCGContext { cgContext in
waveformDrawer.draw(waveform: samples, on: cgContext, with: configuration.with(size: size), renderer: renderer)
}
}
.onAppear {
waveformDrawer.shouldDrawSilencePadding = shouldDrawSilencePadding
}
.onChange(of: shouldDrawSilencePadding) { newValue in
waveformDrawer.shouldDrawSilencePadding = newValue
}
}
}
#if DEBUG
@available(iOS 15.0, macOS 12.0, *)
struct WaveformLiveCanvas_Previews: PreviewProvider {
struct TestView: View {
@State var show: Bool = false
var body: some View {
VStack {
if show {
WaveformLiveCanvas(
samples: [],
configuration: liveConfiguration,
renderer: LinearWaveformRenderer(),
shouldDrawSilencePadding: show
)
}
}.onAppear() {
show = true
}
}
}
static var liveConfiguration: Waveform.Configuration = Waveform.Configuration(
style: .striped(.init(color: .systemPink, width: 3, spacing: 3))
)
static var previews: some View {
TestView()
}
}
#endif