iOS 응용 (swift)
[iOS - swift] UIGraphicsBeginImageContextWithOptions, 그래픽 UIImage 생성
jake-kim
2021. 3. 29. 23:52
UIGrahpicsBeginImageContext란
- bitmap image context를 생성하는 함수: 그림을 그려서 UIImage로 저장하는 것
- context란? 코어 이미지의 모든 프로세싱은 CIContext내에서 수행: 렌더링 과정과 렌더링에 필요한 리소스를 더 정밀하게 컨트롤 할수 있게 해주는 객체
- iOS 4.0 이전부터 지원했던 함수이며 scale = 1.0으로 bitmap image context를 만들어 주는것
(retina 디스플레이에서 선명하지 않을 수 있는 단점)

UIGraphicsBeginImageContextWithOptions란
- iOS 4.0+ 지원하는 함수이며 scale 값을 지정할 수 있어서 retina 디스플레이에 장점

- 인수
- size: bitmap context 사이즈 (= 생성될 이미지의 사이즈)
- opaque: 생성될 이미지의 투명도 여부 (투명도가 있으면 true, 단 불투명도일때가 퍼포먼스가 높은 특징 존재)
- scale: 0.0이면 디바이스의 화면에 맞게 이미지가 결정
- iOS 4.0 이전부터 지원했었던 UIGraphicsBeginImageContext는 scale이 1.0으로 고정 - ex) UIGraphicsBeginImagecontextWithoptions(CGSize(width: 100, height: 100, true, 2.0))의미: 투명도를 가지고 있으며 이미지의 크기는 200*200
UIGraphicsBeginImageContextWithOptions 사용 방법
ex) CALyaer 객체를 UIImage객체로 변환
func transformLayerToImage(layer: CALayer) -> UIImage {
...
}
- graphic context 옵션 설정 / 객체 생성
func transformLayerToImage(layer: CALayer) -> UIImage {
UIGraphicsBeginImageContextWithOptions(layer.bounds.size, false, 0.0) // <- 추가
guard let context = UIGraphicsGetCurrentContext() else { // <- 추가
return
}
}
- context에 layer객체를 rendering
func transformLayerToImage(layer: CALayer) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(layer.bounds.size, false, 0.0)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
layer.render(in: context) // <- 추가
}
- redering된 context에서 UIImage 객체 획득
func gradientColor(bounds: CGRect, gradientLayer: CALayer) -> UIColor? {
UIGraphicsBeginImageContextWithOptions(gradientLayer.bounds.size, false, 0.0)
gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext() // <- 추가
}
- context 옵션 해제
func gradientColor(bounds: CGRect, gradientLayer: CALayer) -> UIColor? {
UIGraphicsBeginImageContextWithOptions(gradientLayer.bounds.size, false, 0.0)
gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext() // <- 추가
return image // <- 추가
}
* UILabel의 text에 색깔 입히는 방법 예제: ios-development.tistory.com/394