Hello there,
I'm having performance issues when drawing with CoreGraphics in my iPhone application, the Idea is to draw a line with the finger. Every suggestion I could find on the internet targeting this problem was:
"cache the lines to a CGLayer, so that the application doesn't have to redraw all those lines over and over again". Now this makes perfect sense, but I can't figure out at all how to exactly store the newest line in a layer and add this layer to the view.
The next code fragment shows that every time the user moves his/her finger the application will store the newest location in a collection.
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject]; //get the touch
CGPoint location = [touch locationInView:self]; //make point from the touch location
[linePoints addObject: [NSValue valueWithCGPoint: location]]; //add the point to a collection
[self setNeedsDisplay]; //calls drawRect:
}
and the function to draw all the lines
-(void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext(); //get the graphics context
for (int i = 0; i < [linePoints count]; i++) //for every point in the linePoints collection
{
if(i > 0)
{
int fromIndex = i-1; //from point index
int toIndex = i; //to point index
CGPoint fromPoint = [[linePoints objectAtIndex: fromIndex] CGPointValue]; //get the from point
CGPoint toPoint = [[linePoints objectAtIndex: toIndex] CGPointValue]; //get the to point
CGFloat white[4] = {1.0f, 1.0f, 1.0f, 1.0f}; //make color
CGContextSetStrokeColor(context, red); //set color
CGContextSetLineWidth(context, 20.0f); //set width
CGContextBeginPath(context); //begin drawing
CGContextMoveToPoint(context, fromPoint.x, fromPoint.y); //from
CGContextAddLineToPoint(context, toPoint.x, toPoint.y); //to
CGContextStrokePath(context); //voila!
}
}
}