Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 根据拾取的图像(从图像选择器)更改图像视图帧_Swift_Image_Imageview_Frames - Fatal编程技术网

Swift 根据拾取的图像(从图像选择器)更改图像视图帧

Swift 根据拾取的图像(从图像选择器)更改图像视图帧,swift,image,imageview,frames,Swift,Image,Imageview,Frames,我有一个图像视图,其中有一个设置的帧,但当用户单击它并更改图像(UIImagePickerController)时,我不知何故需要将图像视图的帧更改为图像的帧 当他们单击图像的“选择”按钮时,这就是我运行的代码 itemImage.contentMode = .scaleAspectFit self.itemImage.image = pickedImage as? UIImage 因此,图像出现在图像视图中,但我需要一些帮助来找到一种方法,使图像视图帧更改为拾取的图像帧 这就是我所说的框架不

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

当他们单击图像的“选择”按钮时,这就是我运行的代码

itemImage.contentMode = .scaleAspectFit
self.itemImage.image = pickedImage as? UIImage
因此,图像出现在图像视图中,但我需要一些帮助来找到一种方法,使图像视图帧更改为拾取的图像帧

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


谢谢

首先,您应该使用以下方法获得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

在我看来,您的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

为什么不
itemage.contentMode=.scaleAspectFill
或调整视图大小-这可能会有帮助:@MohmmadS不会稍微拉伸图像吗?@rbaldwin如何实现您提到的链接?是的,但通常我们会更改图像大小,而不是imgView,我们将图片放入其中,而不是图片的视图,想象一下有一个4k图像。。idk您打算如何在其中调整imgView的大小