Information Technology Reference
In-Depth Information
NOTE
While it's possible to load an image from a file in
drawRect:
and use the contents as wallpaper, there are easier
ways to achieve this result; more details are provided later in this chapter. Similarly, there are easier ways to cre-
ate a single color static background.
drawRect:
is ideal for more complex effects.
In this example,
drawRect:
code creates a static three-color gradient fill, using C functions from the Core
Graphics framework. The code illustrates how a subclass of
UIView
can be customized to create a specific ef-
fect. In practice, you can add extra features to any of the existing methods defined for
UIView
, or you can add
your own custom properties and methods, as needed.
The code does the following:
It creates and clears a
context,
an area of memory used for graphics.
It creates a
color space
object, which holds information about colors.
It creates an array of three colors from RGB components.
It creates a color-gradient object using the array.
It draws a rectangle in the view, allowing for the 20-pixel status bar.
It draws a gradient fill from the top left to the bottom right of the view.
It cleans up by restoring the original graphics state and releasing used memory.
- (void)drawRect:(CGRect)rect {
CGPoint startFill, endFill;
CGContextRef aContext = UIGraphicsGetCurrentContext();
CGContextClearRect(aContext, rect);
CGContextSetShouldAntialias(aContext, YES);
CGColorSpaceRef myRGB = CGColorSpaceCreateDeviceRGB();
size_t num_locations = 3;
CGFloat locations [3] = {0.0, 0.5, 1.0};
CGFloat components [12] =
{1.0, 0.0, 0.0, 1.0,
0.0, 1.0, 0.0, 1.0,
0.0, 0.0, 1.0, 1.0};
CGGradientRef myGradient =
CGGradientCreateWithColorComponents(myRGB,
components,
locations,
num_locations);
CGContextSaveGState(aContext);
CGContextAddRect(aContext, CGRectMake(0, 0, 320, 460));
CGContextClip(aContext);
startFill = CGPointMake(0, 0);
endFill = CGPointMake(320, 460);
CGContextDrawLinearGradient(aContext,
myGradient,
startFill,
endFill,