在 iOS 上的后台线程中绘图
我有一个具有一些非常复杂的绘图逻辑的视图(它是从 GIS 数据绘制的地图视图)。在主线程上执行此绘图会锁定 UI 并使应用程序无响应。我想将绘图移至后台线程,例如使用 NSOperation。
构建这个结构的最佳方法是什么?
我当前正在绘制到内存外 CGContext,然后将其转换为 CGImageRef,然后将其发送到视图以在主线程上进行 blit。不幸的是,这会占用大量内存,并且似乎不再使用 GPU 加速,因为它速度慢了很多。有没有某种方法可以从后台线程直接绘制视图?我知道 UIKit 不是多线程安全的,但也许有某种方法可以在我绘图时锁定视图?
I have a view with some very complex drawing logic (it's a map view that draws from GIS data). Doing this drawing on the main thread locks up the UI and makes the app unresponsive. I want to move away the drawing to a background thread with for example an NSOperation.
What is the best way to structure this?
I am currently drawing to an off memory CGContext and then convert that to a CGImageRef which I send to the view to blit on the main thread. Unfortunately this uses up a lot of memory and it seems that the GPU acceleration is no longer used as it is quite a bit slower. Is there some way of drawing directly to the view from a background thread? I know that UIKit isn't multi-thread safe but maybe there is some way of locking the view while I'm doing the drawing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除了 iOS 4.0 之外,绘图是线程安全的。您可能需要自己创建一个 CGContext,但没有理由不能在后台线程上绘图。
也就是说,大多数 UIKit 操作都不是。如果您需要执行这些操作,您始终可以在后台线程中进行准备,然后在需要时使用
performOnMainThread
。甚至还有waitUntilDone
。也就是说,显然您应该使用 NSOperation 和 NSOperationQueue 。Beyond iOS 4.0, drawing is thread safe. You might need to create a
CGContext
yourself, but there is no reason you cannot draw on a background thread.That said, most UIKit operations are not. If you need to do those, you can always prepare in a background thread, and then use
performOnMainThread
when needed. There's evenwaitUntilDone
. That said, you should useNSOperation
andNSOperationQueue
, apparently.我在 iPhone 上从未遇到过这种情况,但在 Mac 上我曾经遇到过类似的问题。
这
应该可以解决问题。
还可以尝试对您的进程进行采样并检查谁在消耗 CPU。这将使 UI 响应迅速且非常快速。
您提到的性能问题可能是由于其他原因造成的。尝试cpu采样过程。它可以让您深入了解谁实际占用了 CPU。
I have never came across such situation on iPhone but on Mac I had similar problem once.
...
This should do the trick.
Also try to sample your process and check who is consuming the CPU. This will make UI responsive and very fast.
The performance problem you mentioned is can be due to something else. Try to cpu sample process. It will give you insight on who is actually taking CPU.