Freddy
Freddy

Reputation: 820

Why does my Coregraphics drawingcode cause lag?

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

Upvotes: 1

Views: 409

Answers (2)

Mike Pollard
Mike Pollard

Reputation: 10195

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

Upvotes: 1

TAKeanice
TAKeanice

Reputation: 521

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

enter image description here

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

Upvotes: 1

Related Questions