【发布时间】:2012-09-20 03:07:17
【问题描述】:
考虑一下在启用 ARC 的 iOS 应用中这个简单的 UIView 子类,它会在触摸屏幕时在视图上进行绘制:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint location = [[touches anyObject] locationInView:self];
int padding = brushSize / 2;
CGRect brushRect = CGRectMake(
location.x - padding, location.y - padding,
brushSize, brushSize
);
[self setNeedsDisplayInRect:brushRect];
}
- (void)drawRect:(CGRect)rect {
NSDate *start = [NSDate date];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawImage(context, rect, brushImage);
NSLog(@"%f", [start timeIntervalSinceNow]);
}
在本例中,brushImage 是一个方形位图,brushSize 是一个描述位图宽度和高度的 int。
我一直得到这样的日志输出:
-0.131658
-0.133998
-0.143314
-0.007132
-0.006968
-0.007444
-0.006733
-0.008574
-0.007163
-0.006560
-0.006958
对 drawRect 的第一次调用比后续调用花费更长的时间来完成,并且 drawRect 此后继续保持快速。只有在视图初始化后的第一次调用时,drawRect 才会很慢。
我在模拟器和我尝试过的所有物理设备中都看到了类似的结果。初始调用总是需要更长的时间才能完成。
为什么 drawRect / CGContextDrawImage 在初始调用时这么慢?更重要的是,我该如何解决这个问题?
【问题讨论】:
标签: iphone objective-c ios core-graphics drawrect