Proper use of UIRectClip to scale a UIImage down to icon size

前端 未结 3 547
清酒与你
清酒与你 2021-02-06 10:07

Given a UIImage of any dimension, I wish to generate a square \"icon\" sized version, px pixels to a side, without any distortion (stretching). How

3条回答
  •  自闭症患者
    2021-02-06 10:08

    I wanted to achieve a similar thing but found the answer from by the original poster didn't quite work. It distorted the image. This may well be solely because he didn't post the whole solution and had changed some of how the variables are initialised:

     (if (size.width > size.height) 
           ratio = px / size.width;
    

    Was wrong for my solution (which wanted to use the largest possible square from the source image). Also it is not necessary to use UIClipRect - if you make the context the size of the image you want to extract, no actual drawing will be done outside that rect anyway. It is just a matter of scaling the size of the image rect and offsetting one of the origin coordinates. I have posted my solution below:

    +(UIImage *)makeIconImage:(UIImage *)image
    {
        CGFloat destSize = 400.0;
        CGRect rect = CGRectMake(0, 0, destSize, destSize);
    
        UIGraphicsBeginImageContext(rect.size);
    
        if(image.size.width != image.size.height)
        {
            CGFloat ratio;
            CGRect destRect;
    
            if (image.size.width > image.size.height)
            {
                ratio = destSize / image.size.height;
    
                CGFloat destWidth = image.size.width * ratio;
                CGFloat destX = (destWidth - destSize) / 2.0;
    
                destRect = CGRectMake(-destX, 0, destWidth, destSize);
    
            }
            else
            {
                ratio = destSize / image.size.width;
    
                CGFloat destHeight = image.size.height * ratio;
                CGFloat destY = (destHeight - destSize) / 2.0;
    
                destRect = CGRectMake(0, destY, destSize, destHeight);
            }
            [image drawInRect:destRect];
        }
        else
        {
            [image drawInRect:rect];
        }
        UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
        UIGraphicsEndImageContext();
    
        return scaledImage;
    }
    

提交回复
热议问题