在iOS上的后台线程中绘图 [英] Drawing in a background thread on iOS

查看:243
本文介绍了在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]];
}

这应该可以解决问题。

This should do the trick.

还尝试对流程进行采样并检查谁在消耗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上的后台线程中绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆