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

前端 未结 8 1565
没有蜡笔的小新
没有蜡笔的小新 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:26

    The solution is also based on olearyj234's solution, but I think this will help more people.

    @IBDesignable
    class DynamicImageView: UIImageView {
    
        @IBInspectable var fixedWidth: CGFloat = 0 {
            didSet {
                invalidateIntrinsicContentSize()
            }
        }
        @IBInspectable var fixedHeight: CGFloat = 0 {
            didSet {
                invalidateIntrinsicContentSize()
            }
        }
    
        override var intrinsicContentSize: CGSize {
            var size = CGSize.zero
            if fixedWidth > 0 && fixedHeight > 0 { // 宽高固定
                size.width = fixedWidth
                size.height = fixedHeight
            } else if fixedWidth <= 0 && fixedHeight > 0 { // 固定高度动态宽度
                size.height = fixedHeight
                if let image = self.image {
                    let ratio = fixedHeight / image.size.height
                    size.width = image.size.width * ratio
                }
            } else if fixedWidth > 0 && fixedHeight <= 0 { // 固定宽度动态高度
                size.width = fixedWidth
                if let image = self.image {
                    let ratio = fixedWidth / image.size.width
                    size.height = image.size.height * ratio
                }
            } else { // 动态宽高
                size = image?.size ?? .zero
            }
            return size
        }
    
    }
    

提交回复
热议问题