简体   繁体   中英

UIKit drawing is thread safe: how do you get a graphics context?

So, as mentioned in this answer and in the iOS 4.0 release notes , UIKit now has some thread-safe drawing facilities:

Drawing to a graphics context in UIKit is now thread-safe. Specifically:

  • The routines used to access and manipulate the graphics context can now correctly handle contexts residing on different threads.
  • String and image drawing is now thread-safe.
  • Using color and font objects in multiple threads is now safe to do.

That's great, but how do you use it?

As far as I'm aware, any time you're not inside -drawRect: you can only draw using the UIKit/UIGraphics stuff if you've created your own context through UIGraphicsBeginImageContext() or UIGraphicsPushContext() , but those functions are not thread safe according to the docs, and -drawRect() is always called on the main thread.

I assume that creating an image context on the main thread and then starting the background method would be a really bad idea, due to race conditions aplenty.

So, how do I use this multithreaded UIKit-based drawing stuff that was introduced in iOS 4? What other ways of getting an active UIKit graphics context have I missed?

PS I know that I could just draw using Core Graphics and be done with it. For various reasons (legacy code) I'd like to continue using the UIKit based drawing methods.

My belief, based on some experience trying it and based on various documents, is that the docs for UIGraphicsPushContext() are incorrect.

I believe UIGraphicsPushContext() is in fact thread safe. The particular indication that this is true is QA1637 , which says "Beginning with iOS 4.0, drawing to a graphics context in UIKit is thread-safe. This includes accessing and manipulating the current graphics stack , drawing images and strings, and usage of color and font objects from secondary threads." (emphasis mine)

I acknowledge that it is always a dicey proposition to assume thread safety in contradiction to the docs. But I believe this is a documentation error. I have opened rdar://11161530 to track it. Please dupe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM