to drawRect or not to drawRect (when should one use drawRect/Core Graphics vs subviews/images and why?)

Stick to UIKit and subviews whenever you can. You can be more productive, and take advantage of all the OO mechanisms that should things easier to maintain. Use Core Graphics when you can’t get the performance you need out of UIKit, or you know trying to hack together drawing effects in UIKit would be more complicated.

The general workflow should be to build the tableviews with subviews. Use Instruments to measure the frame rate on the oldest hardware your app will support. If you can’t get 60fps, drop down to CoreGraphics. When you’ve done this for a while, you get a sense for when UIKit is probably a waste of time.

So, why is Core Graphics fast?

CoreGraphics isn’t really fast. If it’s being used all the time, you’re probably going slow. It’s a rich drawing API, which requires its work be done on the CPU, as opposed to a lot of UIKit work that is offloaded to the GPU. If you had to animate a ball moving across the screen, it would be a terrible idea to call setNeedsDisplay on a view 60 times per second. So, if you have sub-components of your view that need to be individually animated, each component should be a separate layer.

The other problem is that when you don’t do custom drawing with drawRect, UIKit can optimize stock views so drawRect is a no-op, or it can take shortcuts with compositing. When you override drawRect, UIKit has to take the slow path because it has no idea what you’re doing.

These two problems can be outweighed by benefits in the case of table view cells. After drawRect is called when a view first appears on screen, the contents are cached, and the scrolling is a simple translation performed by the GPU. Because you’re dealing with a single view, rather than a complex hierarchy, UIKit’s drawRect optimizations become less important. So the bottleneck becomes how much you can optimize your Core Graphics drawing.

Whenever you can, use UIKit. Do the simplest implementation that works. Profile. When there’s an incentive, optimize.

Leave a Comment