1. UIGraphicsBeginImageContextWithOptions
extension UIImage {
func resize(targetSize: CGSize) -> UIImage? {
let size = self.size
let widthRatio = targetSize.width / size.width
let heightRatio = targetSize.height / size.height
let newSize = CGSize(width: size.width * min(widthRatio, heightRatio),
height: size.height * min(widthRatio, heightRatio))
let rect = CGRect(origin: .zero, size: newSize)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
self.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
2. UIGraphicsImageRenderer
extension UIImage {
func resize(targetSize size: CGSize) -> UIImage? {
let renderer = UIGraphicsImageRenderer(size: size)
let image = renderer.image { _ in
self.draw(in: CGRect(origin: .zero, size: size))
}
return image
}
}
3. CGImageSourceCreateThumbnailAtIndex
extension UIImage {
func resize(targetSize size: CGSize) -> UIImage? {
guard let data = self.pngData() else { return nil }
guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }
let options: [CFString: Any] = [
kCGImageSourceThumbnailMaxPixelSize: max(size.width, size.height),
kCGImageSourceCreateThumbnailFromImageAlways: true
]
guard let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil }
return UIImage(cgImage: cgImage)
}
}
각각의 차이에 대해서는 아래 블로그 참고
https://ios-development.tistory.com/1591
https://ios-development.tistory.com/1592
'iOS > Swift' 카테고리의 다른 글
[Swift/Xcode] 하나의 빌드 설정에 여러 xconfig을 등록하는 방법 (0) | 2024.07.27 |
---|---|
[Swift] Coordinator 패턴으로 화면 전환 +DIContainer(Swinject) (0) | 2024.07.13 |
[Swift] Dictionary(grouping:by:) (0) | 2024.07.12 |
[Swift] KeyPath 이해하기 (0) | 2024.07.11 |