Domanda

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!

È stato utile?

Soluzione

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.

Altri suggerimenti

The reason you cannot reuse it is because you are drawing to a buffer that gets committed after a short duration. By that time, it's too late to add any changes.

Recreating the entire path might be very inefficient based on the number of points received, and the frequency. Redrawing a mutable path is fairly cheap. So, you should probably save a Mutable path somewhere, and each time you add a point to it, use setNeedsDisplay or whatever to redraw. Don't worry about the performance of this approach until you actually profile/measure it and it proves inefficient.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top