2016-07-27 168 views
0

我以前(在主線程上同步)繪製圖像,效果很好。下面是我畫什麼:如何使用GCD繪製圖像?

The final image

但現在,我想利用GCD重繪它提高了性能。但我有像下面的圖片我轉向使用GCD代碼後:

image with problem

爲什麼灰色圓圈變爲人行道?


這是最新的代碼(異步):

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

感謝您的幫助! :)

回答

0

您可以將您的繪圖代碼移動到後臺線程。你只需要確保在主線程上更新實際的UI。在StackOverflow上似乎有一些很好的資源可以涵蓋這一點。退房: Having UIView drawRect occur in a background thread

+0

是的,你是對的,我已經通過在後臺線程中繪製內容解決了這個問題,當繪圖操作完成時,我在主線程的UI上顯示圖像。 –

0

您必須在主線程上執行所有UI操作。

+0

我認爲CGContext操作在iOS 4.0以上是線程安全的。 –