[swift] Swift Core Graphics의 이미지 처리 기능
Swift에서 이미지를 생성하고 수정할 수 있는 강력한 라이브러리로 Core Graphics가 있다. Core Graphics는 이미지 그리기, 색상 관리, 이미지 변환, 그리기 연산 등 다양한 이미지 처리 기능을 제공한다.
이미지 그리기
Core Graphics를 사용하여 사각형, 원, 선 등의 기본 도형을 그리거나 이미지를 채우고, 선을 그을 수 있다.
import UIKit
func drawRectangle() -> UIImage? {
let size = CGSize(width: 100, height: 100)
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(UIColor.red.cgColor)
context?.fill(CGRect(x: 0, y: 0, width: 100, height: 100))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
이미지 변환
Core Graphics를 사용하여 이미지를 회전, 크기 조정, 자르기 및 이동할 수 있다.
import UIKit
func resizeImage(image: UIImage, newSize: CGSize) -> UIImage? {
UIGraphicsBeginImageContext(newSize)
image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
색상 관리
Core Graphics를 사용하여 이미지의 픽셀 데이터를 직접 제어하여 색상을 변경하거나 이미지 필터를 적용할 수 있다.
import UIKit
func applyFilter(to image: UIImage) -> UIImage? {
guard let inputCGImage = image.cgImage else { return nil }
let context = CIContext(options: nil)
let inputCIImage = CIImage(cgImage: inputCGImage)
let filter = CIFilter(name: "CIPhotoEffectMono")
filter?.setValue(inputCIImage, forKey: kCIInputImageKey)
if let outputCIImage = filter?.outputImage,
let cgImage = context.createCGImage(outputCIImage, from: outputCIImage.extent) {
return UIImage(cgImage: cgImage)
}
return nil
}
위와 같이 Core Graphics를 사용하면 이미지를 다루고, 변환하고, 필터를 적용하는 등 다양한 이미지 처리 기능을 사용할 수 있다.
이 외에도 Core Graphics에는 다른 다양한 기능들이 제공되며, 이를 통해 다양한 이미지 처리 작업을 수행할 수 있다.
참고문헌:
- Apple Developer Documentation - Core Graphics
- Hacking with Swift - Core Graphics Tutorial for Swift: Lines, Rectangles, and Gradients