[SwiftUI] UIImage crop 저장

조영훈·2022년 8월 27일
0
// 자를 원본 이미지
let inputImage = UIImage(data: mediaData)!

// 보이는 화면과 이미지의 비율 계산
let imageViewScale = max(inputImage.size.width / UIScreen.main.bounds.width,
                         inputImage.size.height / UIScreen.main.bounds.height)

// Scale cropRect to handle images larger than shown-on-screen size
// 아직 이유는 모르겠지만 CGImage로 변환하면 사진이 90도 회전되어서 저장이 됨
// 그래서 width랑 height를 바꿔서 적용
let cropZone = CGRect(x: 0,
                      y: 0,
                      width:  self.photoheight * imageViewScale,
                      height: self.photoWidth * imageViewScale)

// 이미지 자르기
guard let cutImageRef: CGImage = inputImage.cgImage?.cropping(to:cropZone)
        else {
            return
        }

// 최종 uiimage 저장
let data = UIImage(cgImage: cutImageRef, scale: inputImage.imageRendererFormat.scale, orientation: inputImage.imageOrientation)

출처 및 참고
Apple developer
advanced swift blog

0개의 댓글