How to resize UIImageView based on UIImage's size/ratio in Swift 3?

前端 未结 8 1539
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 19:01

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

8条回答
  •  遥遥无期
    2020-11-28 19:30

    The solution I used is based on olearyj234's solution, but makes having no image take up essentially no space (or more specifically the minimum iOS will accept). It also uses ceil to avoid problems which can occur with non-integer values when UIImageView's are embedded in things like scrolling cells.

    class FixedWidthAspectFitImageView: UIImageView
    {
    
        override var intrinsicContentSize: CGSize
        {
            // VALIDATE ELSE RETURN
            // frameSizeWidth
            let frameSizeWidth = self.frame.size.width
    
            // image
            // ⓘ In testing on iOS 12.1.4 heights of 1.0 and 0.5 were respected, but 0.1 and 0.0 led intrinsicContentSize to be ignored.
            guard let image = self.image else
            {
                return CGSize(width: frameSizeWidth, height: 1.0)
            }
    
            // MAIN
            let returnHeight = ceil(image.size.height * (frameSizeWidth / image.size.width))
            return CGSize(width: frameSizeWidth, height: returnHeight)
        }
    
    }
    

提交回复
热议问题