UIImageView aspect fit and center

前端 未结 10 1009
执笔经年
执笔经年 2020-12-07 09:48

I have an image view, declared programmatically, and I am setting its image, also programmatically.

However, I find myself unable to set the image to both fit the as

10条回答
  •  青春惊慌失措
    2020-12-07 10:15

    This subclass uses center if the image is not larger than the view, otherwise it scales down. I found this useful for a UIImageView that changes the size.

    The image it displays is smaller than the view for large sizes, but larger than the view for small sizes. I want it only to scale down, but not up.

    class CenterScaleToFitImageView: UIImageView {
        override var bounds: CGRect {
            didSet {
                adjustContentMode()
            }
        }
    
        override var image: UIImage? {
            didSet {
                adjustContentMode()
            }
        }
    
        func adjustContentMode() {
            guard let image = image else {
                return
            }
            if image.size.width > bounds.size.width ||
                image.size.height > bounds.size.height {
                contentMode = .ScaleAspectFit
            } else {
                contentMode = .Center
            }
        }
    }
    

提交回复
热议问题