Skip to content

Instantly share code, notes, and snippets.

@b3ll
Created September 5, 2019 05:26
Show Gist options
  • Save b3ll/518209bd506e47f07b4246c66b706836 to your computer and use it in GitHub Desktop.
Save b3ll/518209bd506e47f07b4246c66b706836 to your computer and use it in GitHub Desktop.
//
// WaveformView.swift
// WaveformSwiftUI
//
// Created by Adam Bell on 9/4/19.
// Copyright © 2019 Adam Bell. All rights reserved.
//
import SwiftUI
struct WaveformView: View {
var data: [Float]
var body: some View {
GeometryReader { geo in
Path { [data = self.data] path in
guard data.count > 0 else { return }
let bounds = geo.frame(in: .local)
let insetBounds = bounds.insetBy(dx: 20.0, dy: 20.0)
let width = insetBounds.width
let height = insetBounds.height
let halfHeight = height / 2.0
let yForData = { (value: Float) in
return insetBounds.minY + halfHeight + (halfHeight * CGFloat(value))
}
path.move(to: CGPoint(x: insetBounds.minX, y: yForData(data[0])))
for i in 1..<data.count {
let x = insetBounds.minX + (width * (CGFloat(i) / CGFloat(data.count)))
let y = yForData(data[i])
path.addLine(to: CGPoint(x: x, y: y))
}
}
.stroke(Color.white, lineWidth: 4.0)
.background(Color.black)
.drawingGroup()
}
}
}
struct WaveformView_Previews: PreviewProvider {
static var previews: some View {
VStack {
Spacer()
WaveformView(data: Wavetables.sine)
.frame(width: nil, height: 280.0, alignment: .center)
Spacer()
}
.background(Color.black)
.edgesIgnoringSafeArea(.all)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment