如何在Swift 3中根据UIImage的大小/比例调整UIImageView的大小? [英] How to resize UIImageView based on UIImage's size/ratio in Swift 3?

查看:1012
本文介绍了如何在Swift 3中根据UIImage的大小/比例调整UIImageView的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请不要标记为重复,我没有找到考虑可用线程的解决方案。

Please do not mark as duplicate, I haven't found a solution considering available threads.

我有一个 UIImageView 并且用户可以以各种格式下载 UIImages 。问题是,我需要 UIImageView 根据给定的Image比例调整大小。

I have a UIImageView and the user is able to download UIImages in various formats. The issue is, that I need the UIImageView to resize based on the given Image's ratio.

目前我是使用 Aspect fit ,但 UIImageView 在其自身的大部分上仍然为空。我想让 UIImageView 根据其内容调整自身大小。例如,如果图片是1:1,4:3,6:2,16:9 ......

Currently I'm using Aspect fit, but the UIImageView remains empty on big parts of itself. I would like to have the UIImageView resize itself based on its content. E.g if the pic is 1:1, 4:3, 6:2, 16:9...

非常感谢帮助。

根据要求,这就是我想要的:

As requested, that is what I want:

我有一个 UIImageView 这是正方形,加载了16:7或其他任何图像,并且 UIImageView 调整大小以适合图像的大小......

I have had an UIImageView that was square, loaded with an Image in 16:7 or whatever and the UIImageView resized to fit the size of the Image...

推荐答案

看起来你想根据图像比例和容器视图的大小来调整ImageView的大小,这里是Swift中的例子(对不起,前一个答案)有一个错误,我修复了它):

It looks like you want to resize an ImageView according to the image ratio and the container view's size, here is the example in Swift (Sorry,the former answer with a bug, I fixed it):

   let containerView = UIView(frame: CGRect(x:0,y:0,width:320,height:500))
   let imageView = UIImageView()

    if let image = UIImage(named: "a_image") {
        let ratio = image.size.width / image.size.height
        if containerView.frame.width > containerView.frame.height {
            let newHeight = containerView.frame.width / ratio
            imageView.frame.size = CGSize(width: containerView.frame.width, height: newHeight)
        }
        else{
            let newWidth = containerView.frame.height * ratio
            imageView.frame.size = CGSize(width: newWidth, height: containerView.frame.height)
        }
    }

这篇关于如何在Swift 3中根据UIImage的大小/比例调整UIImageView的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆