본문 바로가기
iOS 🍎/iOS

Core Graphics로 두 이미지 합성하기

by yongmin.Lee 2022. 3. 17.

Core Graphics란?

  • Core Graphics is Apple's vector drawing framework
  • Core Graphics를 통해  path-based drawing, transformations, color management, offscreen rendering, patterns, gradients and shadings, image data management, image creation, and image masking 등등의 작업을 할 수 있다
  • Core Graphics를 이용하여 2차원 좌표계상에서 CGContext에 렌더 정보들을 기록하고 이를 UIImage로 만들어 낼 수 있다

 

Core Graphics 좌표 공간

  • Core Graphics 좌표 공간은 UIKit과 동일하게 CGRect로 좌표와 가로세로를 나타낸다
  • 하지만 좌측상단에서 시작하여 오른쪽하단으로 나아가는 uikit과 달리 Core Graphics의 원점은 좌측하단이고 오른쪽상단 방향으로 뻗어나간다
  • 따라서 context.translateBy() 함수로 원점을 조정, context.scaleBy() 함수로 스케일 조정 하여 uikit과 동일 하게 맞춰주면 계산이 편하다!

 

BlendMode

두 이미지를 context상에 그릴때 blendmode를 설정해주면 다음과 같은 합성 결과 물을 얻을 수 있다

 

예시 코드

func render(fistImage:UIImage, secondImage:UIImage ) -> UIImage {

	// 첫번째 이미지 사이즈 만큼의 context 생성
	UIGraphicsBeginImageContext(fistImage.size)
    guard let context = UIGraphicsGetCurrentContext() else {return}
    
    // core graphics의 원점과 스케일을 uikit과 동일하게 설정
    context.translateBy(x: 0, y: fistImage.size.height)
    context.scaleBy(x: 1.0, y: -1.0)
    
    // 이미지 합성
    let drawRect = CGRect(
    	x: 0,
        y: 0,
        width: secondImage.size.widht,
        height: secondImage.size.height
    )
    context.setBlendMode(.sourceAtop)
    context.draw(secondImage.cgImage!, in: drawRect)
    
    // 결과
    let mergedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    
    return mergedImage
}

 

 

 

 

 

 

 

 

 

참고자료

https://developer.apple.com/documentation/coregraphics

https://www.raywenderlich.com/8003281-core-graphics-tutorial-getting-started

'iOS 🍎 > iOS' 카테고리의 다른 글

CALayer vs UIView  (0) 2022.03.18
Animation 1 - UIView Animation  (0) 2022.03.17
Pixel, PT, PPI  (0) 2022.03.16
Deep Link : URI Scheme vs Universal Link  (0) 2022.03.16
ReactorKit 1  (0) 2022.03.15