iOS 应用程序 Xcode 中 Swift 的绘图性能

Drawing performance with Swift in Xcode for iOS app

我有一个画线的功能,编辑如下。它似乎在模拟器中运行良好,但是存在性能问题,当 运行 在较旧的 iPhone (2011) 和较新的 iPad (2014) 上时,线条绘制缓慢。我认为这个问题是由于为收到的每个 touchesMoved 事件创建一个新的 CGContext

例如,我如何在 touchesBegan 时调用 let context = UIGraphicsGetCurrentContext() 一次? (即如何使 context 成为可以调用一次的 public 变量?)

任何其他提高性能的技巧将不胜感激。谢谢。

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {

    autoreleasepool {

    UIGraphicsBeginImageContextWithOptions(view.frame.size, false, 0.0)

    let context = UIGraphicsGetCurrentContext()

    ...
    ...
    ...

    UIGraphicsEndImageContext()

    }

}

不在touchesMoved中执行绘图代码。您应该存储更新绘图所需的任何内容(可能是触摸位置),然后调用 setNeedsDisplay。这将强制调用包含所有绘图代码的 drawRect: 。您不需要创建上下文,只需使用 UIGraphicsGetCurrentContext().

这是一个人为设计的 UIView 子类示例,它在最新的触摸点下方绘制了一个红色圆圈。

class DrawView: UIView {

  let circleSize:CGFloat = 50.0
  var lastTouchPoint:CGPoint?

  override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    lastTouchPoint = touches.first?.locationInView(self)
    self.setNeedsDisplay()
  }

  override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    lastTouchPoint = touches.first?.locationInView(self)
    self.setNeedsDisplay()
  }

  override func drawRect(rect: CGRect) {
    if let touchPoint = lastTouchPoint {
      let context = UIGraphicsGetCurrentContext()
      CGContextSetRGBFillColor (context, 1, 0, 0, 1);
      CGContextFillEllipseInRect(context, CGRectMake(touchPoint.x - circleSize/2.0, touchPoint.y - circleSize/2.0, circleSize , circleSize))
    }
  }
}