Search code examples
iphoneiosipadcalayerdrawrect

Drawing graphs on iOS: Use layers or override drawRect?


Reading through the documentation, it's not clear to me if overriding a UIView's drawRect or using layers is appropriate.

I am going to be rendering two kinds of graphs. A line graph and a single-bar bar graph. Both will have ticks along the axis and text aligned with the ticks. Below I only show four ticks per axis, but there could be more.

  1. What is the better way of drawing the ticks? Should I use an individual layer for each tick, or render them all at once on a separate view using drawRect?

  2. Is there another way to render the text other than using a separate UILabel for each?

  3. For the bar graph, I am using a CAGradientLayer for the bar. For the line graph, is it even possible to render this using layers?

Sample Graph

enter image description here


Solution

  • In the end, I used a combination of overriding drawRect and CALayer/CAShapeLayer. Having now been through the process of implementing it all from scratch, I would go with shapes and layers.

    The shapes and layers approach is plenty performant, and is a more robust solution. In the end it takes less code if you are doing things like animation.