Skip to content

Instantly share code, notes, and snippets.

@mmuszynski
Created February 19, 2018 16:59
Show Gist options
  • Save mmuszynski/ca11ce06e351e4454cca56c1d816868b to your computer and use it in GitHub Desktop.
Save mmuszynski/ca11ce06e351e4454cca56c1d816868b to your computer and use it in GitHub Desktop.
/// Creates an array of values to display
///
/// Averages values and performs in batches in the background
func resetDrawValues() {
guard values.count > 0 else {
print("load data first")
return
}
drawValues = []
drawPoints = []
//let logValues = self.values
let binCount = Int(self.bounds.size.width / resolutionWidth)
let binSize = values.count / binCount
if self.shapeLayer == nil {
setupLayer()
}
DispatchQueue.global().async {
let threshhold: Float = -50
var logValues: [Float] = self.values.map {
let value = 10 * log10f( $0 )
return value < threshhold ? threshhold : value
}
var drawValuesBuffer = [Float]()
var drawPointsBuffer = [NSPoint]()
var drawValuesCount = 0
var nextThreshhold = logValues.count / 5
for i in stride(from: 0, to: logValues.count, by: binSize) {
let range = i..<(i+binSize >= logValues.count ? logValues.count - 1 : i+binSize)
let bin = logValues[range]
let value = bin.reduce(0,+) / Float(bin.count)
let point = NSPoint(x: CGFloat(drawValuesCount) / CGFloat(binCount),
y: CGFloat(value - threshhold))
drawValuesBuffer.append(value - threshhold)
drawPointsBuffer.append(point)
drawValuesCount += 1
if i > nextThreshhold {
DispatchQueue.main.async {
self.drawValues.append(contentsOf: drawValuesBuffer)
self.drawPoints.append(contentsOf: drawPointsBuffer)
self.refreshLayer()
}
drawValuesBuffer.removeAll(keepingCapacity: true)
drawPointsBuffer.removeAll(keepingCapacity: true)
nextThreshhold += logValues.count / 5
}
}
DispatchQueue.main.async {
self.drawValues.append(contentsOf: drawValuesBuffer)
self.drawPoints.append(contentsOf: drawPointsBuffer)
self.refreshLayer()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment