The simplest way to resize an UIImage?

前端 未结 30 2608
迷失自我
迷失自我 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
    慢半拍i (楼主)
    2020-11-21 22:56

    I've also seen this done as well (which I use on UIButtons for Normal and Selected state since buttons don't resize to fit). Credit goes to whoever the original author was.

    First make an empty .h and .m file called UIImageResizing.h and UIImageResizing.m

    // Put this in UIImageResizing.h
    @interface UIImage (Resize)
    - (UIImage*)scaleToSize:(CGSize)size;
    @end
    
    // Put this in UIImageResizing.m
    @implementation UIImage (Resize)
    
    - (UIImage*)scaleToSize:(CGSize)size {
    UIGraphicsBeginImageContext(size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0.0, size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    
    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, size.width, size.height), self.CGImage);
    
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return scaledImage;
    }
    
    @end
    

    Include that .h file in whatever .m file you're going to use the function in and then call it like this:

    UIImage* image = [UIImage imageNamed:@"largeImage.png"];
    UIImage* smallImage = [image scaleToSize:CGSizeMake(100.0f,100.0f)];
    

提交回复
热议问题