Fitting a UIImage in UIImageView

2019-05-20 08:53发布

问题:

I need to resize my UIImage according to the size of UIImageView. My image is too small, so i need to scale it up. I was not able to do it using:

self.firstImage.contentMode = UIViewContentModeScaleAspectFit;

Please help.

回答1:

You just need 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);
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}

Or look at these links :

http://nanostuffs.com/Blog/?p=586

http://www.abdus.me/ios-programming-tips/resize-image-in-ios/



回答2:

In Swift 3.0 , it will be

func imageWithImage(image:UIImage, scaledToSize newSize:CGSize ) -> UIImage {

    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
    image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.width))
    let newImage : UIImage  = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext();
    return newImage;

}


回答3:

Please follow below link. Hope you will get solution.

How to use UIImageView Content Mode ?

Thanks.



回答4:

try with this:

self.imageView.contentMode   = UIViewContentModeScaleAspectFill;
self.imageView.clipsToBounds = YES;