I need to draw text on a background thread to save it as an image.
I'm doing
UIGraphicsPushContext()
[NSString drawInRect:]
UIGraphicsPopContext()
The code works fine, but sometimes it crashes in drawInRect when I'm also drawing on the main thread at the same time.
I tried to use NSAttributedString as suggested here: UIStringDrawing methods don't seem to be thread safe in iOS 6. But [NSAttributedString drawInRect:] doesn't seem to render anything on my background thread for some reason. Main thread seems to work fine though.
I've been thinking of using Core Text, but looks like Core Text also has similar problem: CoreText crashes when run in multiple threads
Is there a thread safe way to draw text?
UPDATE: If I run this code, it almost immediately crashes in drawInRect with EXC_BAD_ACCESS:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), NO, 0);
UIFont* font = [UIFont systemFontOfSize:14.0f];
for (int i = 0; i < 100000000; i++) {
[@"hello" drawInRect:CGRectMake(0, 0, 100, 100) withFont:font];
}
UIGraphicsEndImageContext();
});
UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), NO, 0);
UIFont* font = [UIFont systemFontOfSize:12.0f];
for (int i = 0; i < 100000000; i++) {
[@"hello" drawInRect:CGRectMake(0, 0, 100, 100) withFont:font];
}
UIGraphicsEndImageContext();
If I remove UIFont and just draw text without font it works fine.
UPDATE: This only seems to crash on iOS 6.1, but seems to work fine on iOS 7.1.