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

前言

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

代码

 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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容