Graphics Programs Reference
In-Depth Information
image and set it as its
thumbnailData
. The
thumbnailData
will be archived with
the
BNRItem
, and every time it is loaded from an archive, it will recreate its
thumb-
nail
from this data.
In
BNRItem.m
, create a getter method for
thumbnail
that will create it from the data
if necessary:
- (UIImage *)thumbnail
{
// If there is no thumbnailData, then I have no thumbnail to return
if (!thumbnailData) {
return nil;
}
// If I have not yet created my thumbnail image from my data, do so now
if (!thumbnail) {
// Create the image from the data
thumbnail = [UIImage imageWithData:thumbnailData];
}
return thumbnail;
}
Now let's turn to the
setThumbnailDataFromImage:
method. This method will
take a full-sized image, create a smaller representation of it in an offscreen context object,
and set the
thumbnail
pointer to the image produced by the offscreen context.
iOS provides a convenient suite of functions to create offscreen contexts and produce im-
ages from them. To create an offscreen image context, you use the function
UIGraph-
icsBeginImageContextWithOptions
. This function accepts a
CGSize
structure
that specifies the width and height of the image context, a scaling factor, and whether the
image should be opaque. When this function is called, a new
CGContextRef
is created
and becomes the current context.
To draw to a
CGContextRef
, you use Core Graphics, just as though you were imple-
menting a
drawRect:
method for a
UIView
subclass. To get a
UIImage
from the
context after it has been drawn, you call the function
UIGraphic-
sGetImageFromCurrentImageContext
.
Once you have produced an image from an image context, you must clean up the context
with the function
UIGraphicsEndImageContext
.
In
BNRItem.m
, implement the following methods to create a thumbnail using an off-
screen context.
- (void)setThumbnailDataFromImage:(UIImage *)image