1

I have a complex Quartz routine in drawRect for a custom UIView subclass. It can take a few seconds to draw. What I'd like is to show a UIActivityIndicator while it is drawing. But then the indicator must stop spinning (and get hidden) after the drawing is complete.

I tried to start the animation of the indicator and then use performSelector for a custom method that simply calls setNeedsDisplay - my thinking is that performSelector will wait until the next run loop, right? In which case, my indicator has time to start on the main thread. This seems to be working, but as soon as I add the code to the end of drawRect to stop the animation, the indicator doesn't show up at all, as if this animation is ending before it's had a chance to begin.

Any suggestions?

I call the drawing like this:

[self.spinner startAnimating];
[self performSelectorOnMainThread:@selector(redraw) withObject:nil waitUntilDone:YES];//tried both YES and NO here

-(void)redraw{
[self.customView setNeedsDisplay];

}

The drawRect: simply has this at the end:

 - (void)drawRect:(CGRect)rect{
  //bunch of drawing
  [self.nav stopSpinner]; // reference to a controller class
   }

In self.nav object is this:

 -(void)stopSpinner{
self.spinner.hidden=YES;
[self.spinner stopAnimating];
}

And the spinner object is initially created like this:

    self.spinner=[[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]autorelease];
    self.spinner.hidden=YES;
    [self.viewController.view addSubview:self.spinner];
4

1 回答 1

0

在后台线程上执行绘图。这不仅可以让您抛出一个活动指示器并让它根据需要进行动画处理,而且绘图本身的速度要快得多。在我的测试中,我发现在后台线程上复杂的 Quartz 绘图速度提高了 10 倍。

这并不难。事实上,它可能非常快,您不需要活动指示器。

这是代码,您可以简单地使用常规UIImageView,然后将其image属性分配给另一个线程的渲染输出:

 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);

  dispatch_async(queue, ^{

    UIGraphicsBeginImageContext(self.bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    //perform some drawing into this context

    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();


    dispatch_sync(dispatch_get_main_queue(), ^{
        self.imageView.image=viewImage;
    });
});
于 2012-08-09T10:45:41.797 回答