setThumbnailDataFromImage method


Could anyone explain me the implementation done by the authors in this methods?

  • (void)setThumbnailDataFromImage:(UIImage *)image
    CGSize origImageSize = [image size];
    CGRect newRect;
    newRect.origin = CGPointZero;
    newRect.size = [[self class] thumbnailSize];
    // How do we scale the image?
    float ratio = MAX(newRect.size.width/origImageSize.width,
    // Create a bitmap image context
    // Round the corners
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:newRect
    [path addClip];
    // Into what rectangle shall I composite the image?
    CGRect projectRect;
    projectRect.size.width = ratio * origImageSize.width;
    projectRect.size.height = ratio * origImageSize.height;
    projectRect.origin.x = (newRect.size.width - projectRect.size.width) / 2.0;
    projectRect.origin.y = (newRect.size.height - projectRect.size.height) / 2.0;
    // Draw the image on it
    [image drawInRect:projectRect];
    // Get the image from the image context, retain it as our thumbnail
    UIImage *small = UIGraphicsGetImageFromCurrentImageContext();
    [self setThumbnail:small];
    // Get the image as a PNG data
    NSData *data = UIImagePNGRepresentation(small);
    [self setThumbnailData:data];
    // Cleanup image contex resources, we’re done

This whole context thing confuses me.

Any help would be appreciated.



More specifically, How is the origin of the context calculated?

projectRect.origin.x and the projectRect.origin.y

How are the formulas derived?



Think of the context as like an object that is part of an array of sorts. The computer can create multiple contexts and it needs to know which one you’re using whenever you use a graphics function, and you tell it by passing the name of the context whenever the program needs to know it (note the *CurrentImageContext function, there’s probably somewhere where it stores the last image context and that function uses that).

The best way to look at the formulas is to draw it out on paper or computer if you can’t visualize the variables. The origin looks like it centers the data from looking at the (Var - Var2) / 2.

Hope that helps a little.