iOS: Using UIView's 'drawRect:' vs. its layer's delegate 'drawLayer:inContext:'

后端 未结 6 1666
无人共我
无人共我 2020-12-04 06:36

I have a class which is a subclass of UIView. I am able to draw stuff inside the view either by implementing the drawRect method, or by implementin

6条回答
  •  青春惊慌失措
    2020-12-04 06:46

    drawRect should only be implemented when absolutely needed. The default implementation of drawRect includes a number of smart optimizations, like intelligently caching the view's rendering. Overriding it circumvents all of those optimizations. That's bad. Using the layer drawing methods effectively will almost always outperform a custom drawRect. Apple uses a UIView as the delegate for a CALayer often - in fact, every UIView is the delegate of it's layer. You can see how to customize the layer drawing inside a UIView in several Apple samples including (at this time) ZoomingPDFViewer.

    While the use of drawRect is common, it's a practice that has been discouraged since at least 2002/2003, IIRC. There aren't many good reasons left to go down that path.

    Advanced Performance Optimization on iPhone OS (slide 15)

    Core Animation Essentials

    Understanding UIKit Rendering

    Technical Q&A QA1708: Improving Image Drawing Performance on iOS

    View Programming Guide: Optimizing View Drawing

提交回复
热议问题