简体   繁体   中英

image doesn't fit in UIImageView

I am a beginner in iOS development and stuck at the following problem.

In .xib file I have button and imageview as displayed in following image.

在此处输入图片说明

Now I did the following to show image in image view and set content mode in .m file.

UIImage *save = UIGraphicsGetImageFromCurrentImageContext();
self.ivCard.image = save;
self.ivCard.contentMode = UIViewContentModeScaleAspectFit;
self.ivCard.clipsToBounds = YES;

Now the result looks like the following image.

在此处输入图片说明

The original image has resolution of 2000x1000, here it is

在此处输入图片说明

The image is automatically cropped from the right side, it should be fit with image view.

Pretty sure you didn't add constraints to the ImageView, the ImageView size it's not the same as the device size.

Add constraints from the ImageView to the borders in the Interface Builder, and it will work.

Check: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/WorkingwithConstraints/WorkingwithConstraints.html

There are 2 ways to achieve it.

  1. You can either go for constraints and add constraints to your image view either from your .xib file or prgrammatically as shown below:

    // align ivCard from the left and right

      [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[ivCard]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(ivCard)]]; 

    // align ivCard from the top and bottom

     [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[ivCard]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(ivCard)]]; 
  2. You can directly set frame for image view using this code:

     CGFloat btnHeight = 20; // Your back button height from xib self.ivCard.frame = CGRectMake(0, btnHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - btnHeight); 

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