I have a buffer that gets filled with float data points every 1/10 of a second. When the data is ready/comes (around 4000 each time), I translate that data into lines.
My problem here, as you may already know, is that the drawing becomes really slow. I'm posting some of my code below.
Here's my custom UIView. This method gets called once.
override func layoutSubviews() {
super.layoutSubviews()
// init stuff for drawing animation
path = UIBezierPath()
yOff = Float(self.bounds.height / 2)
lastPoint = CGPoint(x: 1.0, y: Double(yOff))
path.move(to: lastPoint)
path.addLine(to: lastPoint)
pathLayer = CAShapeLayer()
pathLayer.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height)
pathLayer.path = path.cgPath
pathLayer.strokeColor = UIColor.red.cgColor
pathLayer.fillColor = nil
pathLayer.lineWidth = 0.2
pathLayer.lineJoin = kCALineJoinBevel
let pathAnimation: CABasicAnimation = CABasicAnimation(keyPath: "strokeEnd")
pathAnimation.duration = 0.1
pathAnimation.fromValue = NSNumber(value: 0.0)
pathAnimation.toValue = NSNumber(value:1.0)
self.layer.addSublayer(pathLayer)
pathLayer.add(pathAnimation, forKey: "strokeEnd")
}
The following method does the actual drawing, which gets called by "setNeedsDisplay" every 1/10 of a second.
override func draw(_ rect: CGRect) {
// this is where the magic (animation) happens
CATransaction.begin()
pathLayer.path = path.cgPath
CATransaction.commit()
}
This is in the viewcontroller. I'm looping through the data points to create a CGPoint for each data. Probably inefficient; any help/idea is welcome:
for _s in samples
{
let currP = CGPoint(x: cX * xModifier, y: yOffSet + (CGFloat(_s)*yModifier))
cX += xLen
self.waveView.path.addLine(to: currP)
ctr = ctr + 1
}
DispatchQueue.main.async {
self.waveView.setNeedsDisplay()
}
Thanks in advance.