【发布时间】:2016-01-25 15:08:03
【问题描述】:
下面的代码通过覆盖触摸绘制平滑曲线,但存在明显的滞后或延迟。该代码使用addCurveToPoint 并在每4 个触摸点后调用setNeedsDisplay,这会导致出现跳跃的外观,因为绘图跟不上手指的移动。为了消除滞后或感知延迟,可以用addQuadCurveToPoint 和addLineToPoint 临时填充接触点1、2、3(直到接触点4)。
如何在代码中实际实现这一点,以在显示最终曲线之前使用临时 Line 和 QuadCurved 线来消除感知滞后?
-
如果下面的类附加到一个
UIView(例如viewOne 或self),我如何在touchesEnded之后将绘图复制到该类之外的另一个UIView(例如viewTwo)?// 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. } }
【问题讨论】:
标签: ios swift drawing uibezierpath