Game Development Reference
In-Depth Information
To actually change the color of the pixels of the
UIView
being drawn, we call
CGContextFillRect
passing in our
context
and the
CGRect backgroundArea
. To draw the foreground rectangle, we repeat
the process, but the width of our top rectangle,
healthArea
, is calculated based the value of the
property
percent
. This indicates that every time the
percent
of the
HealthBar
changes, we have
to redraw the
HealthBar
. To make sure this happens, we have to provide our own implementation
of
setPercent:
instead of relying on the default implementation that would be provided by a
synthesized property. Listing 7-12 shows the custom implementation of
setPercent:
for the class
HealthBar
.
Listing 7-12. HealthBar.m (setPercent:)
-(void)setPercent:(float)aPercent{
if (percent != aPercent){
percent = aPercent;
if (percent < 0){
percent = 0;
}
if (percent > 1){
percent = 1;
}
[self setNeedsViewUpdated:YES];
}
setPercent:
. First we check to see if the values of
percent
(the backing variable for the property) and the passed in value
aPercent
have different values.
If they do, we set
percent
to
aPercent
and we normalize the values by ensuring it is between the
values 0 and 1. Lastly, we call
setNeedsViewUpdate:
with
YES
. This ensures that the
HealthBar
will be
redrawn during the next step in the animation. Let's now take a look at how the
Bullet
class is drawn.
Drawing the Bullet Class
We have looked at the class
HealthBar
and inspected how it is drawn. We only used a single
drawing function,
CGContextFillRect
, to create our visual effect. Of course, there are many, many
more drawing functions that allow you to create any visual effect you want. We are not going to
cover all of these functions, but there is fantastic documentation available online. That being said,
let's take a look at the drawing implementation of the class
Bullet
. See Listing 7-13.
Listing 7-13. Bullet.m (drawRect:WithContext:InRect:)
-(void)drawActor:(Actor*)anActor WithContext:(CGContextRef)context InRect:(CGRect)rect{
CGContextAddEllipseInRect(context, rect);
CGContextClip(context);
CGFloat locations[2];
locations[0] = 0.0;
locations[1] = 1.0;