iphone – Most efficient way for partially drawing an UIView in drawRect: – Education Career Blog

I’m using setNeedsDisplayInRect: as much as possible in my UIView subclass, but I don’t know what to do in drawRect:. What is the best way to detect which parts of the UIView have to be drawn? Right now I’ve divided my UIView into several CGRect‘s. For each CGRect I’m calling CGRectContainsRect() to check whether that CGRect needs to be drawn or not. Is that the correct way, or is there a better way?


You’ll want to draw any rect that is even partially in the invalidated rect, so you’ll want to use CGRectIntersectsRect(). Having said that, I’ve seen few cases where it makes sense to partially draw UIViews — unless you have a very large single view inside of a scroll view, you may as well draw the whole thing.


You’re looking at a classic spatial partitioning task. Depending on your view complexity, you can use different strategies to find out what needs to be drawn. If your scene is very simple, then drawing everything or partitioning the scene into discrete areas and doing your bounding rectangle check is fine. For very complex scenes, there are several good data structures (such as octrees) for representing your scene as a tree, and performing spacial queries for objects within a given region.

Check out the topic of Spacial Partitioning on Wikipedia: http://en.wikipedia.org/wiki/Space_partitioning

Leave a Comment