Why does my Coregraphics drawingcode cause lag?

丶灬走出姿态 提交于 2019-12-24 07:38:23

问题


I'm working on an drawing app for iPhone. It works fine for like 5 seconds in the iPhone simulator but as more I draw it gets more laggy. When I test it on the device it gets even more laggy and I can't even draw a simple tree. When I check how high percent the processor is running at in xcode it usually go between 97-100%. Is there any way to fix this?

(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];
}

回答1:


When running instruments on your method, I got the following results:

What that tells me:

  • Setting up a new context every time you want to draw something is
    waste of time. consider only setting it up once, store it somewhere, and you save almost a third of the time, the method currently needs
  • drawImage is the other most-consuming part. It will be enough to set that only once!
  • all other calls are almost negligible



回答2:


There's a great talk about graphics performance including a demo and code walkthrough of a drawing app here:

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

The iOS App Performance: Graphics and Animations video



来源:https://stackoverflow.com/questions/22011115/why-does-my-coregraphics-drawingcode-cause-lag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!