The simplest way to resize an UIImage?

前端 未结 30 2692
迷失自我
迷失自我 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条回答
  •  猫巷女王i
    2020-11-21 23:02

    @Paul Lynch's answer is great, but it would change the image ratio. if you don`t want to change the image ratio, and still want the new image fit for new size, try this.

    + (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    
    // calculate a new size which ratio is same to original image
    CGFloat ratioW = image.size.width / newSize.width;
    CGFloat ratioH = image.size.height / newSize.height;
    
    CGFloat ratio = image.size.width / image.size.height;
    
    CGSize showSize = CGSizeZero;
    if (ratioW > 1 && ratioH > 1) { 
    
        if (ratioW > ratioH) { 
            showSize.width = newSize.width;
            showSize.height = showSize.width / ratio;
        } else {
            showSize.height = newSize.height;
            showSize.width = showSize.height * ratio;
        }
    
    } else if (ratioW > 1) {
    
        showSize.width = showSize.width;
        showSize.height = showSize.width / ratio;
    
    } else if (ratioH > 1) {
    
        showSize.height = showSize.height;
        showSize.width = showSize.height * ratio;
    
    }
    
    //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(showSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, showSize.width, showSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;}
    

提交回复
热议问题