简体   繁体   中英

UIViewContentModeScaleAspectFit in UIImageView does not work correctly

I try to fit an Image into my UIImageView which is called imgBack I define my UIImageView in the header as IBOutlet

IBOutlet UIImageView *imgBack;

in my viewDidLoad function I set the contentMode like this:

imgBack.contentMode = UIViewContentModeScaleAspectFit;

But after I load an image into imgBack like this:

imgBack.image = [UIImage imageWithContentsOfFile: imagePath];

it does not scale to fit into the imageview

This is the picture I load into imgBack: image i try to load

And this is how it looks like in the view: image in UIImageView

As you see, the image does not fit into the View. Does anyone know why?

If changing ImageView contentMode does not work for you, then you can try to resize the image to fit in Image View with help of following code

UIImage *originalImage = [UIImage imageWithContentsOfFile: imagePath];
imgBack.image = [self resizeImage: originalImage imageSize: imgBack.size];

and add this code to your ViewController

-(UIImage*)resizeImage:(UIImage *)image imageSize:(CGSize)size
    {
        UIGraphicsBeginImageContext(size);
        [image drawInRect:CGRectMake(0,0,size.width,size.height)];
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        //here is the scaled image which has been changed to the size specified
        UIGraphicsEndImageContext();
        return newImage;

    }

Attach the image to UIImageView first and then change the content mode

imgBack.image = [UIImage imageWithContentsOfFile: imagePath];
imgBack.contentMode = UIViewContentModeScaleAspectFill;
imgBack.clipsToBounds = YES;
below are the mode try and check
UIViewContentModeScaleToFill,
    UIViewContentModeScaleAspectFit,      // contents scaled to fit with fixed aspect. remainder is transparent
    UIViewContentModeScaleAspectFill,     // contents scaled to fill with fixed aspect. some portion of content may be clipped.
    UIViewContentModeRedraw,              // redraw on bounds change (calls -setNeedsDisplay)
    UIViewContentModeCenter,              // contents remain same size. positioned adjusted.
    UIViewContentModeTop,
    UIViewContentModeBottom,
    UIViewContentModeLeft,
    UIViewContentModeRight,
    UIViewContentModeTopLeft,
    UIViewContentModeTopRight,
    UIViewContentModeBottomLeft,
    UIViewContentModeBottomRight,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM