在 iOS 上的后台线程中绘图

Drawing in a background thread on iOS(在 iOS 上的后台线程中绘图)

本文介绍了在 iOS 上的后台线程中绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些非常复杂的绘图逻辑的视图(它是一个从 GIS 数据中绘制的地图视图).在主线程上执行此绘图会锁定 UI 并使应用程序无响应.我想通过 NSOperation 将绘图移至后台线程.

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?

我目前正在绘制到内存外的 CGContext,然后将其转换为 CGImageRef,我将其发送到视图以在主线程上进行 blit.不幸的是,这会占用大量内存,并且似乎不再使用 GPU 加速,因为它的速度相当慢.有没有办法从后台线程直接绘制到视图?我知道 UIKit 不是多线程安全的,但也许有一些方法可以在我绘制时锁定视图?

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?

推荐答案

我从来没有在 iPhone 上遇到过这种情况,但在 Mac 上我曾经遇到过类似的问题.

I have never came across such situation on iPhone but on Mac I had similar problem once.

  1. 使用 CGLayer委托离线上下文的绘图活动.
  2. 尝试为当前的 NSRunLoop 添加计时器,并按时间间隔执行您的图形命令.它应该看起来像这样......
  1. Use CGLayer to delegate drawing activity of offline contexts.
  2. Try add timer for current NSRunLoop and on timed interval execute your graphic commands. It should look something like this...

...

kRenderFPS 25.0 //This is Maximum value

renderTimer = [[NSTimer timerWithTimeInterval:(1.0 / (NSTimeInterval)kRenderFPS) target:viewobject selector:@selector(RenderUI:) userInfo:nil repeats:YES] retain];


[[NSRunLoop currentRunLoop] addTimer:renderTimer forMode:NSDefaultRunLoopMode];


[[NSRunLoop currentRunLoop] addTimer:renderTimer forMode:NSModalPanelRunLoopMode];


[[NSRunLoop currentRunLoop] addTimer:renderTimer forMode:NSEventTrackingRunLoopMode];

//In view class
-(void)RenderUI:(id)param
{
    [self setNeedsDisplayInRect:[self bounds]];
}

这应该可以解决问题.

还可以尝试对您的进程进行采样并检查谁在消耗 CPU.这将使 UI 响应迅速且非常快速.

Also try to sample your process and check who is consuming the CPU. This will make UI responsive and very fast.

您提到的性能问题可能是由于其他原因.尝试 cpu 示例过程.它将让您深入了解谁实际占用了 CPU.

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.

这篇关于在 iOS 上的后台线程中绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 iOS 上的后台线程中绘图

基础教程推荐