Weekoding

[Swift] UIView와 CALayer 본문

공부 노트(Swift)

[Swift] UIView와 CALayer

Weekoding 2023. 1. 24. 23:42

Interface Builder를 사용하거나 Code를 이용하여 화면을 그릴 때, UIView가 그 주인공이 된다.

이런 저런 코드를 찾아보다 보면 CALayer라는 개념도 발견하게 될 것일터.

두 객체에 대한 속성 모두 분명히 우리가 보이는 화면에 적용이 되는 모양인데.... 둘은 무슨 차이일까??

/* 
 신기하게도, View에 적용하는 backgroundColor는 UIColor를 받지만,
 Layer에 적용하는 backgroundColor는 CGColor를 받는다.
 UIColor와 CGColor 차이점은 다음 시간에..
*/

self.view.backgroundColor = .blue
self.view.layer.backgroundColor = .init(red: 0, green: 102, blue: 255, alpha: 1.0)

 

 

📂  UIView 

: 스크린 위 사각형 공간 속의 내용들을 관리하는 객체.

Views are the fundamental building blocks of your app’s user interface,
and the UIView class defines the behaviors that are common to all views.

- View들은 App UI의 기본 구성요소가 되는 block이며,

   UIView 클래스모든 View들에게 공통되는 행위들을 정의한 클래스이다.

 

일반 View 뿐만 아니라 StackView, ImageView 등등은 모두 UIView로부터 갈라져 나온 SubClasses들이다.

 

그리고 View객체는 User와 상호작용하는 주된 경로이기 때문에, 다음과 같은 책임들이 있다고 한다.

  • Drawing and Animation
    • View는 자신의 사각형 공간 내에서 UIKit이나 Core Graphics를 이용해 content를 그릴 수 있다.
    • 특정 View 속성에 대해 Animation을 구현할 수 있다.(frame, bounds, center, transform, alpha, backgroundColor)
  • Layout and subView management
    • View는 0개 혹은 그 이상의 subview들을 포함할 수 있다.(parent-child 관계 형성)
    • View는 자신의 subView의 position이나 size를 조절할 수 있다.
    • AutoLayout을 이용하여, View 계층 변화에 따라 view를 resizing 또는 repositioning 하는 규칙을 만들 수 있다.
  • Event handling
    • View는 UIResponder의 subclass이므로, touch 등의 이벤트에 응답할 수 있다.
    • View에 보통의 제스쳐들을 다루기 위해 gesture recognizer를 설치할 수 있다.

그리고, framebounds로 View의 형상이 정의된다. 이 두 properties는 나중에 따로 다루어보겠다.

frame: Superview의 좌표 시스템 내에서의 자신의 위치/크기

bounds: 자신의 좌표시스템 내에서의 자신의 위치/크기

 

 

 

📂  CALayer

: Image-based content를 관리하고, 그 content에 대한 animation을 구현할 수 있게 해주는 객체.

Layers are often used to provide the backing store for views but can also be used without a view to display content.

A layer’s main job is to manage the visual content that you provide but the layer itself has visual attributes that can be set, such as a background color, border, and shadow.
In addition to managing visual content, the layer also maintains information about the geometry of its content (such as its position, size, and transform) that is used to present that content onscreen.

- Layer는 종종 view들에 대한 백업 공간으로 사용되지만, content를 나타내기 위해 view 없이 사용될 수 있다.

   

   Layer의 주요 역할은 개발자가 제공하는 visual content를 관리하는 것이다.

   그러나 레이어 자체도 설정할 수 있는 시각적 속성들(backgroundColor, border, shadow)이 있다.

   visual content를 관리하는 것에 추가적으로,

   Layer는 content가 화면에 보여지는 것에 대한 형상값(content의 position, size, transform 등)을 유지(관리)하고 있다.

 

 

UIView와의 관계에 대한 문장도 발견할 수 있었다.

If the layer object was created by a view, the view typically assigns itself as the layer’s delegate automatically,
and you should not change that relationship. 

- View로부터 생성된 Layer객체라면, 일반적으로는 View가 자동으로 자신(View)에게 Layer의 Delegate를 할당하게 된다.

  그리고 해당 관계를 변경해서는 안된다.

 

 

 

📂  UIView vs CALayer

iOS App을 사용할 때, 부드러운 화면의 움직임을 제공하기 위한 노력으로 GPU와 관련된 변천사가 다음과 같다고 한다.

OpenGL → Core Graphics → Core Animation → UIKit

OpenGL은 GPU에 빠르게 엑세스 할 수 있었지만, 코드 양이 아주 많아진다는 것이 단점이었다. 

발전에 따라 점점 코드량은 간소해 지고, LowLevel → HighLevel로 그래픽 작업에 접근할 수 있도록 발전하게 되었다.

그러나 이러한 단순화로 UIKit은 OpenGL보다 사용성은 높아졌지만,  상대적으로 이전의 것들보다 제한된 기능을 제공하게 되었다. 

 

결론적으로, UIKit은 아주 단순한 레이아웃과 이벤트 핸들링 외의 Animation 행위는 Core Animation에게 위임하게 된 것이다.

 

그래서 둘 사이는 세 가지 특징을 가지게 되었다.

  • UIView는 하나의 CALayer(root)를 갖는다.
  • CALayer(root) 여러개의 SubLayer를 가질 수 있다.
  • UIView의 SubViews는 UIView의 CALayer(root) 위에 얹혀지는 것.

Gesture Response나 추가적인 CALayer가 필요 없는 상황 등이라면,

UIView를 여러 개 그리는 것 보다 Draw/Animation에 특화된 CALayer를 여러 개 그리는 것이 훨씬 가볍다고 한다.

이 외 shouldRasterize, drawsAsynchronously처럼 효율적인 Draw/Animation 구현을 위한 프로퍼티들도 제공한다.

 

shouldRasterize:  CALayer를 최초 한 번만 렌더링 할 것 인지 지정하는 프로퍼티(모양은 변하지 않을 때 이용)

drawsAsynchronously: CALayer를 그리는 작업을 Background Thread에서 수행할지를 지정하는 프로퍼티(default: false)

 

 

정리해 보면 아래와 같다.

  UIView CALayer
제공 UIKit Core Animation
실행 스레드 메인 스레드 별도의 스레드
UIResponder O (tap, touch 등의 Gesture 인식 가능) X
특징 최소 하나의 CALayer를 wrapping하고 있음 Drawing 및 Animation 구현 측면에서
UIKit보다 우수함
동작 범위 모바일에서만 등작
(Mac - AppKit)
모바일, Mac모두 동일

 

그래서 비로소 UIView와 CALayer가 모두 계층(hierachy)구조를 갖고 있다는 것과,

UIView의 superView - subViews, CALayer의 superLayer(root) - subLayers 관계를 이해하게 되었다.

 

 

 

 

 

 

📌 마치며

View와 Layer관련 메소드를 접할 때마다 궁금했었다.

addSubview(), addSubLayer(), removeFromSuperview(), removeFromSuperLayer(),

bringSubviewToFront(), sendSubviewToBack() 같은 것들 말이다.

그리고 superview / subviews, superlayer / sublayers 프로퍼티들도 본 적이 있어서 공부하게 되었다.

막상 공부해보니 걱정과는 달리 생각보다 단순한 개념인 것 같다.

역시 알고 쓰는 것은 느낌이 다르다.

 

 

 

오류 및 지적사항은 댓글로 남겨주시면 감사하겠습니다!

참고 :

https://developer.apple.com/

https://babbab2.tistory.com/53

https://ios-development.tistory.com/977

Comments