views:

96

answers:

1

I'm in the process of making a simple drawing program for the iPhone. At the moment, touch events add their location to a list which is connected with a bunch of CGContextAddLineToPoint calls which are redrawn in every call to drawRect.

I'm running into performance issues at fairly low numbers of lines (they are transparent, though), so I tried drawing everything into a CGLayer. Now, instead of drawing each line every frame, it draws each line only once and draws the CGLayer to the screen every frame.

        CGContextRef backgroundContext = CGLayerGetContext(pathBuffer);
        CGContextSetLineWidth(backgroundContext, 2.0);
        CGContextSetLineCap(backgroundContext, kCGLineCapButt);
        CGContextSetStrokeColorWithColor(backgroundContext, [pathColor CGColor]);

        if([[touchPoints objectAtIndex:0] continuesToNextPoint])
        {
            CGContextMoveToPoint(backgroundContext, [[touchPoints objectAtIndex:0] point].x, [[touchPoints objectAtIndex:0] point].y);
            CGContextAddLineToPoint(backgroundContext, [[touchPoints objectAtIndex:1] point].x, [[touchPoints objectAtIndex:1] point].y);
            CGContextStrokePath(backgroundContext);
        }

        //remove it from touchpoints
        [touchPoints removeObjectAtIndex:0];
    }

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawLayerAtPoint(context, CGPointMake(0, 0), pathBuffer);

This, if anything, is SLOWER than what I was doing before. Am I doing something wrong? Would I be better served drawing to a UIImage or something? Thanks.

A: 

What you should be doing is inserting a CALayer into one of your views, updating the layer, and then calling setNeedsDisplayInRect: with the bounds of the area that has changed on the layer, which causes it to update. If you try to update the entire screen, it's going to be slow.

Are you using Instruments to figure out what parts are slow? I recommend using it to learn about what parts are slowing you down.

lucius
It looks like a good 30% of the processing time is going to CGContextStrokePath.
spookyjon
Thanks for the heads up on Instruments, by the way--if you can't tell, I'm pretty new to this.
spookyjon
Thanks, that fixed the problem.
spookyjon