UIImageView 리사이징?
UIImageView의 Content Mode 중 Aspect Fit의 경우 원본 비율을 유지하여 UIImageView에 채워지게 된다.
이렇게 원본 비율을 유지하려다보니, UIImageView의 넓이 혹은 높이에 따라서 빈 공간이 발생하게 된다.
높이가 낮은 경우 좌우 빈 공간이 생긴다.

높이가 딱 맞는 경우, 이상적이다.

높이가 너무 큰 경우, 상하 빈 공간이 생긴다.

만약 고정된 사이즈의 사진만을 보여준다면, 높이나 넓이 값을 고정해두면 되지만 늘 다른 사이즈의 이미지를 보여줘야 한다면 어떻게 빈 공간을 제거해야 할까.
extension UIImageView {
var contentClippingRect: CGRect {
guard let image = image else { return bounds }
guard contentMode == .scaleAspectFit else { return bounds }
guard image.size.width > 0 && image.size.height > 0 else { return bounds }
let scale: CGFloat
if image.size.width > image.size.height {
scale = bounds.width / image.size.width
} else {
scale = bounds.height / image.size.height
}
let size = CGSize(width: image.size.width * scale, height: image.size.height * scale)
let x = (bounds.width - size.width) / 2.0
let y = (bounds.height - size.height) / 2.0
return CGRect(x: x, y: y, width: size.width, height: size.height)
}
}
// 사용 예제
if self.imageView.contentClippingRect.width <= self.imageViewWidth.constant {
let padding = self.imageViewWidth.constant - self.imageView.contentClippingRect.width
self.imageViewWidth.constant = self.imageView.contentClippingRect.width + padding
} else {
self.imageViewHeight.constant = self.imageView.contentClippingRect.height
}
결과
