图像不适合 UIImageView

image doesn't fit in UIImageView

我是 iOS 开发的初学者,遇到了以下问题。

在 .xib 文件中,我有按钮和图像视图,如下图所示。

现在我执行了以下操作以在图像视图中显示图像并在 .m 文件中设置内容模式。

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

现在结果如下图所示。

原图分辨率为2000x1000,这里是

图片自动从右侧裁剪,应该适合图片视图。

很确定您没有向 ImageView 添加约束,ImageView 大小与设备大小不同。

在 Interface Builder 中将 ImageView 的约束添加到边框,它会起作用。

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

有两种方法可以实现。

  1. 您可以从您的 .xib 文件或以编程方式寻求约束并向您的图像视图添加约束,如下所示:

    //从左到右对齐ivCard

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

    // ivCard上下对齐

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[ivCard]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(ivCard)]];
    
  2. 您可以使用此代码直接设置图像视图的框架:

    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);