0

I drawn an image previously (on main thread, synchronously), it works well. Below is what I drawn:

The final image

But now, I'd like to utilize GCD to redraw it for improving performance. But I got an image like below after I turn the code to use GCD:

image with problem

Why the gray circle goes sideway?


This is the latest code (asynchronously):

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)
})

Before, the code is (synchronously, this works well, but not what I want, I prefer to utilize GCD):

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

At last, the buildCircle function:

    /// 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()
}

Appreciate your help! :)

Rex Tsao
  • 65
  • 1
  • 13

2 Answers2

0

You have to do all UI operations on the main thread.

Gargoyle
  • 9,590
  • 16
  • 80
  • 145
0

You can move your drawing code to a background thread. You just need to be sure to update the actual UI back on the main thread. There seems to be a few good resources on StackOverflow that cover this. Check out: Having UIView drawRect occur in a background thread

Community
  • 1
  • 1
D.C.
  • 15,340
  • 19
  • 71
  • 102
  • Yes, you are right, I've already fixed that problem via drawing content in a background thread, and when the drawing operation complete, I show the image on the UI in the main thread. – Rex Tsao Jul 27 '16 at 06:24