为什么我的Coregraphics绘图代码造成滞后?

我正在为iPhone绘制应用程序。 它在iPhone模拟器的5秒内工作正常,但随着越来越多,我得出它更加滞后。 当我在设备上testing时,它会变得更加迟钝,我甚至无法画出一棵简单的树。 当我检查处理器在xcode上的运行百分比时,通常在97-100%之间。 有没有什么办法解决这一问题?

(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; currentPoint = [touch locationInView:self.view]; UIGraphicsBeginImageContext(CGSizeMake(320, 568)); [drawImage.image drawInRect:CGRectMake(0, 0, 320, 568)]; CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0); CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0, 1, 0, 1); CGContextBeginPath(UIGraphicsGetCurrentContext()); CGPathMoveToPoint(path, NULL, lastPoint.x, lastPoint.y); CGPathAddLineToPoint(path, NULL, currentPoint.x, currentPoint.y); CGContextAddPath(UIGraphicsGetCurrentContext(),path); CGContextStrokePath(UIGraphicsGetCurrentContext()); [drawImage setFrame:CGRectMake(0, 0, 320, 568)]; drawImage.image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); lastPoint = currentPoint; [self.view addSubview:drawImage]; } 

在你的方法上运行仪器时,我得到了以下结果:

在这里输入图像说明

那告诉我:

  • 每次你想画东西的时候build立一个新的上下文是
    浪费时间。 考虑只设置一次,将其存储在某个地方,几乎可以节约三分之一的时间,目前需要的方法
  • drawImage是另一个最耗费部分。 只设置一次就足够了!
  • 所有其他的电话几乎可以忽略不计

有一个关于graphics性能的好消息,包括一个绘图应用程序的演示和代码演练:

https://developer.apple.com/videos/wwdc/2012/

iOS应用程序性能:graphics和animationvideo