The simplest way to resize an UIImage?

前端 未结 30 2654
迷失自我
迷失自我 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 22:43

    Here's a modification of the category written by iWasRobbed above. It keeps the aspect ratio of the original image instead of distorting it.

    - (UIImage*)scaleToSizeKeepAspect:(CGSize)size {
        UIGraphicsBeginImageContext(size);
    
        CGFloat ws = size.width/self.size.width;
        CGFloat hs = size.height/self.size.height;
    
        if (ws > hs) {
            ws = hs/ws;
            hs = 1.0;
        } else {
            hs = ws/hs;
            ws = 1.0;
        }
    
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextTranslateCTM(context, 0.0, size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
    
        CGContextDrawImage(context, CGRectMake(size.width/2-(size.width*ws)/2,
            size.height/2-(size.height*hs)/2, size.width*ws,
            size.height*hs), self.CGImage);
    
        UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
        UIGraphicsEndImageContext();
    
        return scaledImage;
    }
    

提交回复
热议问题