The simplest way to resize an UIImage?

前端 未结 30 2603
迷失自我
迷失自我 2020-11-21 22:38

In my iPhone app, I take a picture with the camera, then I want to resize it to 290*390 pixels. I was using this method to resize the image :

UIImage *newI         


        
30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 23:06

    The simplest way is to set the frame of your UIImageView and set the contentMode to one of the resizing options.

    Or you can use this utility method, if you actually need to resize an image:

    + (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
        //UIGraphicsBeginImageContext(newSize);
        // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
        // Pass 1.0 to force exact pixel size.
        UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
        [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
        UIGraphicsEndImageContext();
        return newImage;
    }
    

    Example usage:

    #import "MYUtil.h"
    …
    UIImage *myIcon = [MYUtil imageWithImage:myUIImageInstance scaledToSize:CGSizeMake(20, 20)];
    

提交回复
热议问题