gpt4 book ai didi

ios - 是否可以使用 Quartz 2D 在另一个线程上制作 UIImage ?

转载 作者:可可西里 更新时间:2023-11-01 06:19:22 24 4
gpt4 key购买 nike

我想移动一些需要几秒钟才能在另一个线程上生成 UIImage 的代码,但是我在使用时遇到上下文错误

    UIGraphicsBeginImageContextWithOptions(size,false,0);

在调用调度生成图像之前,我尝试执行的每个操作都显示“无效上下文 0x0”。这是可能吗?

最佳答案

What's New in iOS: iOS 4.0是这样说的:

  • 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.

听起来你试过这样的事情:

UIGraphicsBeginImageContextWithOptions(size,false,0);
dispatch_async(someQueue, ^{
[UIColor.whiteColor setFill];
UIRectFill(0, 0, 20, 20);
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.imageView.image = image;
});
};

这行不通,因为每个线程都有自己的图形上下文堆栈(从 iOS 4.0 开始)。你需要这样做:

dispatch_async(someQueue, ^{
UIGraphicsBeginImageContextWithOptions(size,false,0);
[UIColor.whiteColor setFill];
UIRectFill(0, 0, 20, 20);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = image;
});
};

更新

documentation UIGraphicsBeginImageContextWithOptions 和其他 UIKit 图形函数现在说

In iOS 4 and later, you may call this function from any thread of your app.

documentation对于 UIColor

Color objects are immutable and so it is safe to use them from multiple threads in your app.

documentation对于 UIFont

Font objects are immutable and so it is safe to use them from multiple threads in your app.

但是documentation对于 UIKit NSString-drawing additions says

The methods described in this class extension must be used from your app’s main thread.

因此,您一定在后台线程中尝试类似[@"hello"drawAtPoint:CGPointZero withAttributes:attrs]的操作。

关于ios - 是否可以使用 Quartz 2D 在另一个线程上制作 UIImage ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9151379/

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