我正在为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]);
}
我会尽快尝试,让你知道,谢谢你的提示。 – Morpheu5 2011-06-01 10:53:26
你好,我只花了四个小时试图了解如何借鉴CGLayers,但我无法完成。任何指针? – Morpheu5 2011-06-07 08:43:23
好的,没关系,我知道了,它工作得很好:) – Morpheu5 2011-06-07 09:24:31