如何使用GCD绘制图像?

How to use GCD to draw image?

我之前绘制了一个图像(在主线程上,同步),效果很好。下面是我画的:

但是现在,我想利用GCD重绘它以提高性能。但是在我将代码转为使用 GCD 后,我得到了如下图像:

为什么灰色圆圈是横向的?


这是最新的代码(异步):

let queue3 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
print("frame: \(self.frame)")
self.attachSunMoon()
self.attachClock(rect)

dispatch_async(queue3, {
   self.buildCircle(circleRadius: self.radius)
})

之前,代码是(同步,这很好用,但不是我想要的,我更喜欢利用 GCD):

print("frame: \(self.frame)")
self.attachSunMoon()
self.attachClock(rect)
self.buildCircle(circleRadius: self.radius)

最后,buildCircle函数:

    /// Draw the big circle
private func buildCircle(circleRadius radius: CGFloat) {

    UIGraphicsPushContext(self.ccontext!)
    defer { UIGraphicsPopContext() }


    print("frame: \(self.frame)")
    // Drawing code
    let center = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
    self.centerPoint = center
    //let radius = max(rect.width, rect.height) - 40
    let startAngle: CGFloat = 0
    let endAngle: CGFloat = 2*π

    let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
    path.lineWidth = self.arcWidth
    clockBorderColor.setStroke()
    path.stroke()
}

感谢您的帮助! :)

您必须在主线程上执行所有 UI 操作。

您可以将绘图代码移至后台线程。您只需要确保在主线程上更新实际的 UI 即可。 Whosebug 上似乎有一些很好的资源涵盖了这一点。查看: Having UIView drawRect occur in a background thread