求解释一段代码,ios开发的
怪我咯
怪我咯 2017-04-17 13:12:34
0
1
309
- (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();
}

关于那两段代码,

  1. 第一段那个比例为什么要取大的?
  2. 第二段代码是计算图片的居中显示位置,为什么要这么计算,为什么这么计算就居中了?

看了半会没看懂,求大神解释

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(1)
迷茫

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!