【问题标题】:Change Image view frame depending on picked image (from image picker) frame SWIFT根据拾取的图像(来自图像选择器)框架更改图像视图框架 SWIFT
【发布时间】:2019-03-03 07:38:39
【问题描述】:

我有一个图像视图,其中有一个设置的框架,但是当用户单击它并更改图像(UIImagePickerController)时,我不知何故需要图像视图的框架更改为图像的框架。

当他们点击图片的选择按钮时,这就是我运行的代码。

itemImage.contentMode = .scaleAspectFit
self.itemImage.image = pickedImage as? UIImage

所以图像出现在图像视图中,但我需要一些帮助来找到一种方法来让图像视图框架更改为拾取的图像框架。

这就是我所说的框架不变的意思。

谢谢

【问题讨论】:

  • 为什么不itemImage.contentMode = .scaleAspectFill
  • 或调整您的视图大小 - 这可能会有所帮助:*.com/questions/8701751/…
  • @MohmmadS 这不是把图像拉长一点吗?
  • @rbaldwin 我将如何实现您提到的链接?
  • 是的,但通常我们更改图像大小而不是我们适合图片的 imgView,而不是图片的视图,想象有一个 4k 图像.. idk 你打算如何调整你的 imgView在里面

标签: swift image imageview frames


【解决方案1】:

首先你应该使用这些方法获得 AspectFitSize:

public func getAspectFitFrame(from: CGSize, to: CGSize) -> (CGRect, CGFloat) {
    let (hfactor, vfactor, factor) = getFactor(from: from, to: to)

    let newWidth = to.width / factor
    let newHeight = to.height / factor

    var x: CGFloat = 0.0
    var y: CGFloat = 0.0

    if hfactor > vfactor {
        y = (from.height - newHeight) / 2
    } else {
        x = (from.width - newWidth) / 2
    }
    return (CGRect(x: x, y: y, width: newWidth, height: newHeight), factor)
}

public func getFactor(from: CGSize, to: CGSize) -> (CGFloat, CGFloat, CGFloat) {
    let hfactor = to.width / from.width
    let vfactor = to.height / from.height
    return (hfactor, vfactor, max(hfactor, vfactor))
}

之后你应该用 newSize 修改你的 imageViewSize :

let (imageFitSize , _) = getAspectFitFrame(from : self.itemImage.frame.size , to : self.itemImage.image.size)
self.image.frame.size = imageFitSize.size

【讨论】:

    【解决方案2】:

    在我看来,您的 imageView 已经应用了一些约束。我建议对其应用大小限制。

    // declare these at the top of the file so that the constraints can be removed when new images are selected
    private var widthConstraint: NSLayoutConstraint?
    private var heightConstraint: NSLayoutConstraint?
    
    // remove old constraint
    widthConstraint?.isActive = false
    // fix the imageview width to that of the picked image
    widthConstraint = itemImage.widthAnchor.constraint(equalToConstant: pickedImage.size.width)
    widthConstraint?.isActive = true
    
    heightConstraint?.isActive = false
    heightConstraint = itemImage.heightAnchor.constraint(equalToConstant: pickedImage.size.height)
    heightConstraint?.isActive = true
    

    【讨论】: