1. 程式人生 > 實用技巧 >iOS根據圖片比例計算顯示大小

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