SBGauge as part of GrooveCoach as a way to indicate which ‘level’ the user was on. When you tapped ‘+’ or ‘-’ the gauge changed accordingly. As part of developing that app I was keen to open source anything I could.
Given the flexibility of this simple library, I thought it would make an interesting code walkthrough.
Drawing the Gauge
SBGauge consists of two
CAShapeLayers: the animating gauge itself and the ‘track’ underneath. The
draw method simply creates two circles with different colors and adds them to the view’s backing layer:
1 2 3 4 5 6
The circles are drawn by the
drawCircleLayer:(UIColor *)color method in
CGRectInset means we draw within the view itself, not on the outside. This is especially if you’re working in interface builder - the gauge shouldn’t bust out of the frame you create for the view.
SBGaugeContext is responsible for calculating how big the segments will be and keeping track of the current ‘step’. It is initialized with the number of segments:
When you tell
stepUp, the current
SBGaugeContext will figure out what the current ‘step’ should now be.
SBGauge will then draw based on this new context.
This decouples the logic surrounding step calculations from the drawing of the view itself.
When the view is redrawn, a
CABasicAnimation is created to animate from the previous gauge step to the current step.
animateProgress uses the gauge layer’s ‘strokeEnd’ animate the length of the gauge:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
You’ll see that
SBGaugeContext handles the calculation of the value itself.
SBGauge doesn’t have any additional built in ‘looks’ but by simply setting the
width property, a number of different styles can be achieved.
The size of the gauge itself is calcuated based on the containing frame (plus some hardcoded tweaking):
This makes it possible to get at least an idea of the size of the view in interface builder.
That’s really all there is to it!
I’ve since experimented with driving the guage using a large number of steps and an
NSTimer which find in the project’s README.
Check it out on Github - I’d love your feedback.