我需要在后台线程上绘制文本以将其另存为图像。
我正在做
UIGraphicsPushContext()
[NSString drawInRect:]
UIGraphicsPopContext()
该代码可以正常工作,但是当我同时在主线程上绘制时,有时它会在drawInRect中崩溃。
我尝试按照此处的建议使用NSAttributedString:UIStringDrawing方法在iOS 6中似乎不是线程安全的。但是由于某种原因,[NSAttributedString drawInRect:]似乎未在我的后台线程上呈现任何内容。主线程似乎工作正常。
我一直在考虑使用Core Text,但看起来Core Text也有类似的问题:在多个线程中运行时CoreText崩溃
有没有一种线程安全的方式来绘制文本?
更新:如果我运行此代码,它几乎立即在EXC_BAD_ACCESS的drawInRect中崩溃:
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();
如果我删除UIFont并仅绘制不带字体的文本,则效果很好。
更新:这似乎只在iOS 6.1上崩溃,但在iOS 7.1上似乎可以正常工作。
由于iOS6(可能更早),您可以在不同的线程上使用这些方法,只要您在同一线程上使用UIGraphicsBeginImageContext ...创建了新的上下文。
drawRect:方法默认为自己线程的当前上下文。
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), NO, 0);
UIFont* font = [UIFont systemFontOfSize:26];
NSString* string = @"hello";
NSAttributedString* attributedString = [[NSAttributedString alloc] initWithString:string attributes:@{NSFontAttributeName:font}];
[attributedString drawInRect:CGRectMake(0, 0, 100, 100)];
UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[UIImagePNGRepresentation(image) writeToFile:@"/testImage.png" atomically:YES];
});
在模拟器上运行该命令,它将结果输出到硬盘驱动器的根目录。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句