iOS根据图片比例计算显示大小

前言

iOS开发中,很多地方使用到图片浏览,这时候就可能需要旋转屏幕查看图片,下面分享一种计算图片旋转大小的方法,在此抛砖引玉。

作为一个开发者,有一个学习的氛围跟一个交流圈子特别重要,这是一个我的iOS交流群:196800191,加群密码:112233,不管你是小白还是大牛欢迎入驻 ,分享BAT,阿里面试题、面试经验,讨论技术, 大家一起交流学习成长!

代码

 func calculationFrame(image: UIImage) -> CGRect {
        var x: CGFloat = 0
        var y: CGFloat = 0
        var width: CGFloat = 0
        var height: CGFloat = 0
        
        var screenWidth: CGFloat
        var screenHeight: CGFloat

        if #available(iOS 11.0, *) {
            screenWidth = UIScreen.main.bounds.size.width - self.view.safeAreaInsets.left - self.view.safeAreaInsets.right
        } else {
            screenWidth = UIScreen.main.bounds.size.width
        }
        if #available(iOS 11.0, *) {
            screenHeight = UIScreen.main.bounds.size.height - self.view.safeAreaInsets.top - self.view.safeAreaInsets.bottom
        } else {
            screenHeight = UIScreen.main.bounds.size.width
        }
        let imageWidth = image.size.width
        let imageHeight = image.size.height
        
        let widthSpace = fabsf(Float(screenWidth - imageWidth))
        let heightSpace = fabsf(Float(screenHeight - imageHeight))
        
        if widthSpace >= heightSpace {
            if screenWidth > imageWidth {
                width = imageWidth * (screenHeight / imageHeight)
                height = imageHeight * (screenHeight / imageHeight)
            }else {
                width = imageWidth / (imageWidth / screenWidth)
                height = imageHeight / (imageWidth / screenWidth)
            }
        }else {
            if screenHeight > imageHeight {
                width = imageWidth * (screenWidth / imageWidth)
                height = imageHeight * (screenWidth / imageWidth)
            }else {
                width = imageWidth / (imageHeight / screenHeight)
                height = imageHeight / (imageHeight / screenHeight)
            }
        }
        x = (self.view.frame.size.width - width) * 0.5
        y = (self.view.frame.size.height - height) * 0.5
        return CGRect.init(x: x, y: y, width: width, height: height)
    }

效果图

总结

希望对大家有帮助,demo地址—>>CLDemo

原文作者:季末微夏

原文地址:https://www.jianshu.com/p/2ad3abc43c1e

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值