在 Swift 中消除绘制 UIBezierPath 平滑线时的滞后延迟

Removing lagging latency in drawing UIBezierPath smooth lines in Swift

下面的代码通过覆盖触摸来绘制平滑的曲线,但是有明显的滞后或延迟。该代码使用 addCurveToPoint 并在每 4 个触摸点后调用 setNeedsDisplay,这会导致画面跳动,因为绘图跟不上手指的移动。为了消除滞后或感知延迟,触摸点 1、2、3(通向触摸点 4)可以暂时用 addQuadCurveToPointaddLineToPoint.

填充
  1. 在显示最终曲线之前,如何通过使用临时线和 QuadCurved 线在代码中实际实现消除感知滞后?

  2. 如果下面的 class 附加到一个 UIView(例如 viewOne 或 self),我如何将绘图复制到另一个 UIView 在 class 之外(例如 viewTwo)在 touchesEnded 之后?

     //  ViewController.swift
    
    import UIKit
    
    class drawSmoothCurvedLinesWithLagging: UIView {
    
        let path=UIBezierPath()
        var incrementalImage:UIImage?
    
        var points = [CGPoint?](count: 5, repeatedValue: nil)
    
        var counter:Int?
    
        var strokeColor:UIColor?
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
    
        override func drawRect(rect: CGRect) {
            autoreleasepool {
                incrementalImage?.drawInRect(rect)
                strokeColor = UIColor.blueColor()
                strokeColor?.setStroke()
                path.lineWidth = 20
                path.lineCapStyle = CGLineCap.Round
                path.stroke()
            }
        }
    
        override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
            counter = 0
    
            let touch: AnyObject? = touches.first
            points[0] = touch!.locationInView(self)
        }
    
        override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
            let touch: AnyObject? = touches.first
            let point = touch!.locationInView(self)
    
            counter = counter! + 1
            points[counter!] = point
    
    
            if counter == 2{
                //use path.addLineToPoint ?
                //use self.setNeedsDisplay() ?
            }
    
            if counter == 3{
                //use path.addQuadCurveToPoint ?
                //use self.setNeedsDisplay() ?
            }
    
            if counter == 4{
                points[3]! = CGPointMake((points[2]!.x + points[4]!.x)/2.0, (points[2]!.y + points[4]!.y)/2.0)
                path.moveToPoint(points[0]!)
                path.addCurveToPoint(points[3]!, controlPoint1: points[1]!, controlPoint2: points[2]!)
    
                self.setNeedsDisplay()
    
                points[0]! = points[3]!
                points[1]! = points[4]!
                counter = 1
            }
        }
    
        override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
            self.drawBitmap()
            self.setNeedsDisplay()
            path.removeAllPoints()
            counter = 0
        }
    
        override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
            self.touchesEnded(touches!, withEvent: event)
        }
    
        func drawBitmap(){
            UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, 0.0)
            strokeColor?.setStroke()
            if((incrementalImage) == nil){
                let rectPath:UIBezierPath = UIBezierPath(rect: self.bounds)
                UIColor.whiteColor().setFill()
                rectPath.fill()
            }
    
            incrementalImage?.drawAtPoint(CGPointZero)
            path.stroke()
            incrementalImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
        }
    
    }
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
    
    }
    
  1. 是的,每隔几个点添加一条曲线会使它出现断断续续的滞后。所以,是的,您可以通过向 points[1] 添加一条线、向 points[2] 添加一条四边形曲线并向 points[3] 添加一条三次曲线来减少这种影响。

    不过,正如您所说,请确保将其添加到单独的路径中。所以,在 Swift 3/4:

    class SmoothCurvedLinesView: UIView {
        var strokeColor = UIColor.blue
        var lineWidth: CGFloat = 20
        var snapshotImage: UIImage?
    
        private var path: UIBezierPath?
        private var temporaryPath: UIBezierPath?
        private var points = [CGPoint]()
    
        override func draw(_ rect: CGRect) {
            snapshotImage?.draw(in: rect)
    
            strokeColor.setStroke()
    
            path?.stroke()
            temporaryPath?.stroke()
        }
    
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            if let touch = touches.first {
                points = [touch.location(in: self)]
            }
        }
    
        override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
            guard let touch = touches.first else { return }
            let point = touch.location(in: self)
    
            points.append(point)
    
            updatePaths()
    
            setNeedsDisplay()
        }
    
        private func updatePaths() {
            // update main path
    
            while points.count > 4 {
                points[3] = CGPoint(x: (points[2].x + points[4].x)/2.0, y: (points[2].y + points[4].y)/2.0)
    
                if path == nil {
                    path = createPathStarting(at: points[0])
                }
    
                path?.addCurve(to: points[3], controlPoint1: points[1], controlPoint2: points[2])
    
                points.removeFirst(3)
    
                temporaryPath = nil
            }
    
            // build temporary path up to last touch point
    
            if points.count == 2 {
                temporaryPath = createPathStarting(at: points[0])
                temporaryPath?.addLine(to: points[1])
            } else if points.count == 3 {
                temporaryPath = createPathStarting(at: points[0])
                temporaryPath?.addQuadCurve(to: points[2], controlPoint: points[1])
            } else if points.count == 4 {
                temporaryPath = createPathStarting(at: points[0])
                temporaryPath?.addCurve(to: points[3], controlPoint1: points[1], controlPoint2: points[2])
            }
        }
    
        override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
            finishPath()
        }
    
        override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) {
            finishPath()
        }
    
        private func finishPath() {
            constructIncrementalImage()
            path = nil
            setNeedsDisplay()
        }
    
        private func createPathStarting(at point: CGPoint) -> UIBezierPath {
            let localPath = UIBezierPath()
    
            localPath.move(to: point)
    
            localPath.lineWidth = lineWidth
            localPath.lineCapStyle = .round
            localPath.lineJoinStyle = .round
    
            return localPath
        }
    
        private func constructIncrementalImage() {
            UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0)
            strokeColor.setStroke()
            snapshotImage?.draw(at: .zero)
            path?.stroke()
            temporaryPath?.stroke()
            snapshotImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
        }
    }
    

    您甚至可以将其与 iOS 9 次预测性接触(正如我所描述的 )结合起来,这可以进一步减少延迟。

  2. 要获取此结果图像并将其用于其他地方,您只需抓取 incrementalImage(我在上面将其重命名为 snapshotImage),然后将其放入图像中另一个视图的视图。

对于 Swift 2 版本,请参阅之前的 revision of this answer