ABOUT ME

woongS, iOS, succesS 삼쓰의 개발 블로그

Today
Yesterday
Total
  • ImageView scaleAspectFit 하고 정렬해주기
    iOS 2020. 4. 23. 16:58
    728x90

    ImageView의 contentMode 중 scaleAspectFit 은 이미지의 비율을 유지하면서 최대한의 크기를 맞춰줍니다. 

    그리고 나머지 부분은 여백으로 남겨두죠.

    문제는 aspectfit을 하면서 동시에 정렬을 할 수는 없다는 것입니다 ㅠㅠ

    자동으로 가운데 정렬이 되어버리죠. 

    아쉽게도 UIImageView에서는 이런 처리를 할 수가 없습니다!! 

     

    따라서 만약 scaleAspectFit을 한 이후에 정렬을 해주고 싶다면 별도로 처리를 해줘야 합니다.

    제가 소개해드릴 방법은
    imageView의 contentMode에서는 scaleAspectFit이 아닌 원하는 대로 정렬을 해주고
    UIImage를 aspectFit 해주는 방법입니다.

    우선 UIImage를 aspectFit 해줄 extension 입니다.

    extension UIImage {
        func aspectFitImage(inRect rect: CGRect) -> UIImage? {
            let width = self.size.width
            let height = self.size.height
            let aspectWidth = rect.width / width
            let aspectHeight = rect.height / height
            let scaleFactor = aspectWidth > aspectHeight ? rect.size.height / height : rect.size.width / width
    
            UIGraphicsBeginImageContextWithOptions(CGSize(width: width * scaleFactor, height: height * scaleFactor), false, 0.0)
            self.draw(in: CGRect(x: 0.0, y: 0.0, width: width * scaleFactor, height: height * scaleFactor))
    
            defer {
                UIGraphicsEndImageContext()
            }
    
            return UIGraphicsGetImageFromCurrentImageContext()
        }
    }
    

     

    이걸 이용해서 Image를 aspectFit해주기만 하면됩니다 :) 

    myImageView.image = UIImage(named: "myImage")?.aspectFitImage(inRect: myImageView.frame)
    myImageView.contentMode = .top
    

     

     

    댓글

Designed by Tistory.