ios - 我的 UIImageView 中的约束有什么问题,为什么我不能在 UIViewController 上拉伸(stretch)图像?

标签 ios swift uiimageview nslayoutconstraint

这是我的现状:

enter image description here

我有一个带有 UIImageViewUIViewController

后者有以下约束:trailing to superview, leading to superview, top space to top layout guide, width等于 320高度等于 820

高度和宽度作为导出连接到我的类(class),我在 viewDidLoad 中设置它们:

@IBOutlet weak var imageHeightconstraint: NSLayoutConstraint!

@IBOutlet weak var imageWidthConstraint: NSLayoutConstraint!

@IBOutlet weak var backgroundImage: UIImageView!

override viewDidLoad(){
    backgroundImage.af_setImageWithURL(NSURL(string: photoURL)!)
    imageHeightconstraint.constant = backgroundImage.image!.size.height
    imageWidthConstraint.constant = self.view.frame.size.width
}

现在,我的图像是这样的:

enter image description here

这是一张 480x640 像素的照片。我尝试在 Storyboard中将模式设置为 centerscale to fillaspect fillaspect fit顶部

例如,这是center:

enter image description here

纵横比:

enter image description here

纵横比填充:

enter image description here

但我不知道如何将这张图片从左向右拉伸(stretch)并保持纵横比,所以整张照片都是可见的,而且它的左右边缘贴在屏幕的左右边缘。 我认为这两个约束可以解决它:

imageHeightconstraint.constant = backgroundImage.image!.size.height
imageWidthConstraint.constant = self.view.frame.size.width

但它不起作用。也许问题是照片的分辨率很低(480x640),所以高度只有那么小?你能给我任何提示,我该如何解决它?

最佳答案

要让图像贴在屏幕的两侧并保持纵横比,请设置以下 4 个约束:

  1. ImageView 的前沿到 SuperView 的前沿。
  2. ImageView 的后缘到 SuperView 的后缘。
  3. ImageView 的顶部边缘到顶部布局指南底部。
  4. 设置纵横比约束:ImageView 宽度等于 ImageView 高度,multiplier 480:640。要设置它,control-在 ImageView 中沿对角线拖动并从弹出窗口中选择 Aspect Ratio。然后将乘数更改为 480:640

    aspect ratio constraint

将图像的内容模式设置为Scale to fill

关于ios - 我的 UIImageView 中的约束有什么问题,为什么我不能在 UIViewController 上拉伸(stretch)图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39713649/

相关文章:

javascript:检查用户代理是否在桌面设备上

ios - 在 Safari View Controller 中隐藏共享选项

swift - 我无法访问自定义类中的函数;无论我尝试什么,它都会出现错误

ios - 更改照片库按钮的颜色

ios - 如何让 UIButton 变成一个圆圈?

Swift:热平移和放大/缩小 imageView 中的图像

ios - 在 Storyboard 中的 didselectrowatindexpath 上推送 View

ios - 快速匹配针头和大海捞针的最佳方法

ios - 如何在新搜索中取消 uitableviewcells 的异步图像加载

ios - 如何创建动态图像