Graphics Programs Reference
In-Depth Information
the screen. So, there is a separate
CGRect
property of
UIView
named
bounds
that
gives the view its size independent of its superview. In
HypnosisView.m
, get the
bounds
rectangle in
drawRect:
after you get a pointer to the drawing context.
- (void)drawRect:(CGRect)dirtyRect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect bounds = [self bounds];
}
The drawing operations you perform on the
CGContextRef
must fall within the
bounds
rectangle; otherwise, they will be clipped to that rectangle. Let's draw a circle in
the center of the
bounds
rectangle. Add the following code to
drawRect:
.
- (void)drawRect:(CGRect)dirtyRect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect bounds = [self bounds];
// Figure out the center of the bounds rectangle
CGPoint center;
center.x = bounds.origin.x + bounds.size.width / 2.0;
center.y = bounds.origin.y + bounds.size.height / 2.0;
// The radius of the circle should be nearly as big as the view
float maxRadius = hypot(bounds.size.width, bounds.size.height) / 4.0;
// The thickness of the line should be 10 points wide
CGContextSetLineWidth(ctx, 10);
// The color of the line should be gray (red/green/blue = 0.6, alpha = 1.0);
CGContextSetRGBStrokeColor(ctx, 0.6, 0.6, 0.6, 1.0);
// Add a shape to the context - this does not draw the shape
CGContextAddArc(ctx, center.x, center.y, maxRadius, 0.0, M_PI * 2.0, YES);
// Perform a drawing instruction; draw current shape with current state
CGContextStrokePath(ctx);
}
Build and run the application. The same blue and red squares are there, but now each
square has a gray circle within it. These gray circles are the result of the
drawRect:
method for instances of
HypnosisView
.
Notice that a view's
backgroundColor
is always drawn regardless of what
drawRect:
does. Typically, you set the
backgroundColor
of a view to clear so that
only
drawRect:
's results show. In
HypnosisterAppDelegate.m
, remove the
code that sets the background color of each of these views.
HypnosisView *view = [[HypnosisView alloc] initWithFrame:viewFrame];
[view setBackgroundColor:[UIColor redColor]];
[[self window] addSubview:view];
CGRect anotherFrame = CGRectMake(20, 30, 50, 50);