gpt4 book ai didi

ios - 如何在iOS中的后台线程上绘制文本?

转载 作者:行者123 更新时间:2023-12-01 17:39:49 25 4
gpt4 key购买 nike

我需要在后台线程上绘制文本以将其另存为图像。

我正在做

UIGraphicsPushContext()
[NSString drawInRect:]
UIGraphicsPopContext()

该代码可以正常工作,但是当我同时在主线程上绘制时,有时它会在drawInRect中崩溃。

我试图按照这里的建议使用NSAttributedString:
UIStringDrawing methods don't seem to be thread safe in iOS 6。但是由于某种原因,[NSAttributedString drawInRect:]似乎未在我的后台线程上呈现任何内容。主线程似乎工作正常。

我一直在考虑使用Core Text,但看起来Core Text也有类似的问题: CoreText crashes when run in multiple threads

有没有一种线程安全的方式来绘制文本?

更新:
如果我运行此代码,它几乎会立即在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];

});

在模拟器上运行该命令,它将结果输出到硬盘驱动器的根目录。

关于ios - 如何在iOS中的后台线程上绘制文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23728994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com