【发布时间】:2015-01-14 21:57:25
【问题描述】:
每次用户触摸移动时,我都会在屏幕上绘制一个 UIBezierPath。这在我的 Mac Pro 上的模拟器上运行良好,但是一旦我将它移到物理设备上,绘图就开始滞后很多。使用仪器,我检查了 CPU 使用率,在用户绘图时它达到了 100%。
这成为一个很大的问题,因为我有一个 NSTimer,它应该以 30 fps 的速度触发,但是当 CPU 因绘图而过载时,计时器仅以 10 fps 左右的速度触发。
如何优化绘图使其不占用 100% 的 CPU?
UITouch* lastTouch;
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
if(lastTouch != nil)
return;
lastTouch = [touches anyObject];
[path moveToPoint:[lastTouch locationInView:self]];
[self drawDot];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if([touches anyObject] == lastTouch)
[self drawDot];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
if([touches anyObject] == lastTouch)
lastTouch = nil;
}
- (void)drawDot
{
if(!self.canDraw)
return;
[path addLineToPoint:[lastTouch locationInView:self]];
[self setNeedsDisplayInRect:CGRectMake([lastTouch locationInView:self].x-30, [lastTouch locationInView:self].y-30, 60, 60)];
}
- (void)drawRect:(CGRect)rect
{
CGColorRef green = [UIColor green].CGColor;
CGContextRef context = UIGraphicsGetCurrentContext();
CGColorRef gray = [UIColor gray].CGColor;
CGContextSetStrokeColor(context, CGColorGetComponents(gray));
[shape stroke];
CGContextSetStrokeColor(context, CGColorGetComponents(green));
[path stroke];
}
【问题讨论】:
-
路径使用 100% 时有多大(多少线段)?
标签: ios objective-c core-graphics drawrect uibezierpath