- (void)setThumbnailDataFromImage:(UIImage *)image
{
CGSize origImageSize = [image size];
// The rectangle of the thumbnail
CGRect newRect = CGRectMake(0, 0, 40, 40);
// Figure out a scaling ratio to make sure we maintain the same aspect ratio
// --------------------
// [START] 这里看不懂 1
float ratio = MAX(newRect.size.width / origImageSize.width,
newRect.size.height / origImageSize.height);
// [END] 这里看不懂 1
// --------------------
// Create a transparent bitmap context with a scaling factor
// equal to that of the screen
UIGraphicsBeginImageContextWithOptions(newRect.size, NO, 0.0);
// Create a path that is a rounded rectangle
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:newRect
cornerRadius:5.0];
// Make all subsequent drawing clip to this rounded rectangle
[path addClip];
// Center the image in the thumbnail rectangle
// --------------------
// [START] 这里看不懂 2
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;
// [END] 这里看不懂 2
// --------------------
// Draw the image on it
[image drawInRect:projectRect];
// Get the image from the image context, keep it as our thumbnail
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
[self setThumbnail:smallImage];
// Get the PNG representation of the image and set it as our archivable data
NSData *data = UIImagePNGRepresentation(smallImage);
[self setThumbnailData:data];
// Cleanup image context resources, we're done
UIGraphicsEndImageContext();
}
关于那两段代码,
看了半会没看懂,求大神解释
His algorithm maintains the original proportions of the image and is centered. However, there is a problem. If the image is smaller than 40x40, it is not processed.
Mac notebook, drag with your finger, the drawing is not good, sorry
First, you get the image scaling ratio and take max, which is based on the short side (if the image is larger than 40x40).
Then your content needs to be centered, then use the algorithm of 2. You can think about it yourself according to the picture below, and you should be able to understand it.
Quartz 2D Drawing