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:
CGContextRef
and only draw line for new point, orUIMutablePath
and add new line of point to the path, then stroke the pathBut I found the problem:
CGContextRef
does not work, why ? (ie I can UIGraphicsGetCurrentContext()
in drawRect
but I cannot keep and use it outside the method)CGContextRef
?Thanks!
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:
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.
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.