iosobjective-cquartz-corecgcontextref

iOS: reuse CGContextRef?


I need to draw lines based on data received from a server, and I tried to avoid redrawing the whole thing every time I receive a new point, so I thought about:

  1. Re-use CGContextRef and only draw line for new point, or
  2. Use UIMutablePath and add new line of point to the path, then stroke the path

But I found the problem:

  1. Re-use CGContextRef does not work, why ? (ie I can UIGraphicsGetCurrentContext() in drawRect but I cannot keep and use it outside the method)
  2. Is redrawing the path as less efficient as redrawing using CGContextRef?

Thanks!


Solution

  • Do not attempt to reuse graphics contexts obtained via UIGraphicsGetCurrentContext(). It's not supported and will lead to unstable behavior.

    If you're having performance problems from repeated calls to drawRect, then you have two strategies that might help:

    1. Decrease how often you call setNeedsDisplay. If network data is coming in rapidly, you could set an NSTimer each time new data comes in. Have the timer fire after, say, 0.5 seconds or more (you'll know better than me what's prudent). If new data comes in before the timer fires, reset the timer. If the timer fires without new data arriving, then call setNeedsDisplay. This will throttle the drawing calls.

    2. If your drawing code is really expensive, you can move it to a background thread using UIGraphicsBeginImageContext and UIGraphicsEndImageContext calls, inbetween which you can do your drawing, then render that context into a UIImage, and pass the UIImage via a completion block back to the main queue. Then you can either draw that image in drawRect, or use it as the image property of a UIImageView.