2011-06-01 87 views
0

我正在为iOS写一个小型绘画应用程序。我在其drawRect:方法中继承了一个执行计算的UIView广告。直到我开始有很多对象(实际上是多段线)时,这一切都很好,然后性能开始下降。其中_strokes是点数组数组。我的第一个想法是将图像制作为ivar,在上下文中绘制图像,将其他笔触绘制到上下文中(使用j = [stroke count] - 2更改j = 0),然后将上下文获取到图像并将其存储回ivar。没有工作。如何在持久画布上绘制并在视图内绘制它?

然后,我尝试了很多其他的道路,但没有真正值得一提,直到我在SO(Quartz2D performance - how to improve)上发现了这个其他问题。不幸的是,它没有像我期望的那样工作,因为我必须保留图像,导致内存警告1,2崩溃。

- (void)drawRect:(CGRect)rect { 
    [super drawRect:rect]; 

    UIGraphicsBeginImageContext(CGSizeMake(1024, 768)); 
    CGContextRef imageContext = UIGraphicsGetCurrentContext(); 

    if(_image != nil) { 
     CGContextDrawImage(imageContext, CGRectMake(0, 0, 1024, 768), [_image CGImage]); 
    } 

    int i, j; 
    for(i = 0; i < [_strokes count]; i++) { 
     NSMutableArray *stroke = [_strokes objectAtIndex:i]; 
     if([stroke count] < 2) { 
      continue; 
     } 
     CGContextSetStrokeColorWithColor(imageContext, [[_penColours objectAtIndex:i] CGColor]); 
     for(j = [stroke count]-2; j < [stroke count]-1; j++) { 
      CGPoint line[] = { 
       [[stroke objectAtIndex:j] CGPointValue], 
       [[stroke objectAtIndex:j+1] CGPointValue] 
      }; 

      CGContextSetLineWidth(imageContext, _brushSize); 
      CGContextSetLineCap(imageContext, kCGLineCapRound); 
      CGContextSetLineJoin(imageContext, kCGLineJoinRound); 

      CGContextAddLines(imageContext, line, 2); 
      CGContextStrokePath(imageContext); 
     } 
    } 

    _image = UIGraphicsGetImageFromCurrentImageContext(); 
    [_image retain]; 
    UIGraphicsEndImageContext(); 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextDrawImage(context, CGRectMake(0, 0, 1024, 768), [_image CGImage]); 
} 

回答

1

它看起来至少有一部分问题是你保留_image,但你永远不会释放它。每次为_image分配一个新值时,都会泄漏前一张图像,并且会很快填满内存。

除此之外,您应该使用CGLayer作为您的屏幕外绘图而不是位图。您可以随时随地绘制图层,然后将其复制到您的-drawRect:方法中的屏幕上。

+0

我会尽快尝试,让你知道,谢谢你的提示。 – Morpheu5 2011-06-01 10:53:26

+0

你好,我只花了四个小时试图了解如何借鉴CGLayers,但我无法完成。任何指针? – Morpheu5 2011-06-07 08:43:23

+0

好的,没关系,我知道了,它工作得很好:) – Morpheu5 2011-06-07 09:24:31