Swift에서 이미지를 다루는 것은 앱 개발 과정에서 매우 중요한 부분입니다. 이미지 크기를 변경하거나 회전, 자르기, 필터 적용 및 기타 조작을 할 때 이미지 프레임워크를 사용할 수 있습니다. iOS 및 macOS 프로젝트에서 이미지 프로세싱을 수행하기 위한 몇 가지 기본적인 방법을 살펴보겠습니다.
이미지 프레임워크 가져오기
UIKit을 사용하는 iOS 프로젝트의 경우, 이미지 처리를 위해 UIKit
에서 제공하는 UIImage
클래스를 사용할 수 있습니다. macOS 프로젝트에서는 NSImage
클래스를 사용합니다. 이미지 프로세싱을 위해 이들 클래스에 구현된 다양한 메서드들을 사용할 수 있습니다.
import UIKit
// 또는
import Cocoa
이미지 크기 변경
이미지 프레임워크는 이미지 크기를 변경하는 손쉬운 방법을 제공합니다. 아래의 예시는 이미지의 크기를 새로운 크기로 변경하는 방법을 보여줍니다.
if let image = UIImage(named: "exampleImage.png") {
let newSize = CGSize(width: 100, height: 100)
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image.draw(in: CGRect(origin: .zero, size: newSize))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
이미지 회전
이미지 프로세싱을 통해 이미지를 회전시킬 수도 있습니다. 아래의 예시는 이미지를 90도 회전시키는 방법을 보여줍니다.
if let image = UIImage(named: "exampleImage.png") {
let rotatedImage = image.rotate(radians: .pi / 2)
}
extension UIImage {
func rotate(radians: CGFloat) -> UIImage {
let rotatedSize = CGRect(origin: .zero, size: size)
.applying(CGAffineTransform(rotationAngle: CGFloat(radians)))
.integral.size
UIGraphicsBeginImageContext(rotatedSize)
if let context = UIGraphicsGetCurrentContext() {
context.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)
context.rotate(by: radians)
draw(in: CGRect(x: -size.width / 2, y: -size.height / 2, width: size.width, height: size.height))
let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return rotatedImage ?? self
}
return self
}
}
이미지 자르기
특정 부분의 이미지만 가져와 사용하고 싶을 때 이미지를 자를 수 있습니다. 아래의 예시는 이미지의 일부분을 잘라내는 방법을 보여줍니다.
if let image = UIImage(named: "exampleImage.png") {
let croppedRect = CGRect(x: 100, y: 100, width: 50, height: 50)
if let croppedImage = image.cgImage?.cropping(to: croppedRect) {
let finalImage = UIImage(cgImage: croppedImage)
}
}
필터 적용
Core Image 프레임워크를 사용하면 이미지에 다양한 필터를 적용할 수 있습니다. 해당 필터들은 이미지를 조작하여 그래픽 효과를 제공합니다.
import CoreImage
if let image = UIImage(named: "exampleImage.png") {
if let ciImage = CIImage(image: image) {
let filter = CIFilter(name: "CISepiaTone")
filter?.setValue(ciImage, forKey: kCIInputImageKey)
filter?.setValue(0.8, forKey: kCIInputIntensityKey)
if let outputImage = filter?.outputImage {
let filteredImage = UIImage(ciImage: outputImage)
}
}
}
위의 예시에서 CISepiaTone
은 세피아 톤의 필터를 적용하며, kCIInputIntensityKey
를 사용하여 필터의 강도를 설정합니다.
Swift에서 이미지 프로세싱을 위한 라이브러리와 프레임워크를 사용함으로써 앱의 사용자 경험을 향상시키고 더욱 흥미로운 기능들을 구현할 수 있습니다.
이러한 이미지 처리 방법 및 기능을 추가하여 앱의 UI 및 기능을 향상시킬 수 있습니다.
참조:
- UIKit Documentation
- Cocoa Documentation
- Core Image Documentation
- UIImage Class Reference
- NSImage Class Reference
- Core Image Filter Reference
좀 더 많은 것을 배우고 싶다면 위의 링크들을 참조해보세요.