I’m trying to flatten some images I get from a server down to 40 x 40 thumbnails, so I can save them in /Library/Caches and use those instead with UITableViewCell’s UIImage.
So far, I know how bake / flatten an image like so:
UIImage *newThumbnail = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];
UIGraphicsBeginImageContext(CGSizeMake(40, 40));
[newThumbnail drawInRect:CGRectMake(0, 0, 40, 40)];
newThumbnail = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[UIImagePNGRepresentation(newThumbnail) writeToFile:imageCachePath atomically:YES];
I’d also like to include rounded corners in the flattened image. But right now, I create the rounded corners by manipulating the layer of the UIImageView that hosts the UIIMage. Like so:
imageView.layer.cornerRadius = 7.0;
imageView.layer.masksToBounds = YES;
imageView.layer.borderColor = [UIColor blackColor].CGColor;
imageView.layer.borderWidth = 1.0;
So how do I include the above layer modifications into the whole UIGraphicsBeginImageContext mechanism? Or is there any better way of doing it?
Option (1), which involves more learning and more work, but is more flexible:
Take a look through the CGContextRef docs.
Figure how to draw a rounded corner path. (There’s a bunch of sample code floating around the internets using the CTM.)
To simulate
cornerRadiusandmasksToBounds, use that path to set a clipping path before drawing your image.To simulate the
borderColorplusborderWidth, set an appropriate stroke color and width and then stroke that path.Option (2):
Try rendering your
UIImageView.layerinto your context withrenderInContext:.