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
}
}
}