SHARE
TWEET

Untitled

a guest Sep 16th, 2019 81 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. //  WaveformView.swift
  3. //  WaveformSwiftUI
  4. //
  5. //  Created by Adam Bell on 9/4/19.
  6. //  Copyright © 2019 Adam Bell. All rights reserved.
  7. //
  8.  
  9. import SwiftUI
  10.  
  11. struct WaveformView: View {
  12.  
  13.   var data: [Float]
  14.  
  15.   var body: some View {
  16.     GeometryReader { geo in
  17.       Path { [data = self.data] path in
  18.         guard data.count > 0 else { return }
  19.  
  20.         let bounds = geo.frame(in: .local)
  21.         let insetBounds = bounds.insetBy(dx: 20.0, dy: 20.0)
  22.  
  23.         let width = insetBounds.width
  24.         let height = insetBounds.height
  25.         let halfHeight = height / 2.0
  26.  
  27.         let yForData = { (value: Float) in
  28.           return insetBounds.minY + halfHeight + (halfHeight * CGFloat(value))
  29.         }
  30.  
  31.         path.move(to: CGPoint(x: insetBounds.minX, y: yForData(data[0])))
  32.  
  33.         for i in 1..<data.count {
  34.           let x = insetBounds.minX + (width * (CGFloat(i) / CGFloat(data.count)))
  35.           let y = yForData(data[i])
  36.           path.addLine(to: CGPoint(x: x, y: y))
  37.         }
  38.       }
  39.       .stroke(Color.white, lineWidth: 4.0)
  40.       .background(Color.black)
  41.       .drawingGroup()
  42.     }
  43.   }
  44. }
  45.  
  46. struct WaveformView_Previews: PreviewProvider {
  47.   static var previews: some View {
  48.     VStack {
  49.       Spacer()
  50.       WaveformView(data: Wavetables.sine)
  51.         .frame(width: nil, height: 280.0, alignment: .center)
  52.       Spacer()
  53.     }
  54.     .background(Color.black)
  55.     .edgesIgnoringSafeArea(.all)
  56.   }
  57. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top