2017년 2월 8일 수요일

CALayer - CATextLayer

CATextLayer 는 그 이름처럼 화면에 글자를 그리기 위한 용도의 CALayer 기반 레이어 클래스이다. UILabel 이나 NSTextField 등에 비해 기능적인 면에서 부실하기는 하지만 아무래도 퍼포먼스 면에서는 우위일 것이다.

아래는 CATextLayer 를 사용하는 예제이다.
let view = UIView(frame: CGRect(x: 0, y: 0, width: 256, height: 256))

let textLayer = CATextLayer()
textLayer.frame = view.bounds

textLayer.string = "This is test with very long string"
textLayer.backgroundColor = UIColor.white.cgColor
textLayer.font = "Helvetica Neue" as CFTypeRef
textLayer.fontSize = 50
textLayer.foregroundColor = UIColor.red.cgColor
textLayer.isWrapped = true
view.layer.addSublayer(textLayer)
Core 라는 이름이 붙어있기 때문에 Core Foundation 의 타입 위주로 써야 한다고 생각하자. 그래서 폰트의 경우 폰트이름을 CFTypeRef 형식으로 넣었고(참고로 macOS의 경우 NSFont 인스턴스는 그대로 이용이 가능하다) 폰트 사이즈를 별도로 지정했다. 물론 색상 또한 CGColorRef 타입으로 지정해야 한다. 그 외에 딱히 어려운 부분은 없을 거라 생각된다.

참고로 isWrapped 프로퍼티를 false 로 바꾸면 한 줄만 표시되며 문자열 뒷 부분이 잘린다. 이 잘림의 스타일(truncationMode) 또한 지정이 가능하니 공식 레퍼런스 매뉴얼을 잘 살펴보자.

string 프로퍼티의 경우 위에서는 문자열을 바로 지정했지만, 이 프로퍼티는 Any? 타입이다. 즉 문자열 말고도 다른걸 지정할 수 있는데 바로 NSAttributedString 이다.
let view = UIView(frame: CGRect(x: 0, y: 0, width: 256, height: 256))

let textLayer = CATextLayer()
textLayer.frame = view.bounds

let attrString = NSMutableAttributedString()

attrString.append(NSAttributedString(
  string: "This", 
  attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 30), 
               NSForegroundColorAttributeName: UIColor.black]))

attrString.append(NSAttributedString(
  string: " is", 
  attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: 25), 
               NSForegroundColorAttributeName: UIColor.red]))

attrString.append(NSAttributedString(
  string: " TEST!", 
  attributes: [NSFontAttributeName: UIFont.italicSystemFont(ofSize: 50), 
               NSForegroundColorAttributeName: UIColor.blue]))

textLayer.string = attrString
view.layer.addSublayer(textLayer)
Swift 3 이전에는 색상키에 대한 값을 CGColorRef 타입으로 지정했었어야 했는데 지금은 평범하게 NSAttributedString 을 쓰던 대로 UIColor 인스턴스를 쓰면 된다. 물론 macOS 의 경우라면 NSColor 인스턴스이다.

NSAttributedString 의 모든 부분을 완벽하게 지원한다고 생각되진 않으니 이상하다면 매뉴얼을 읽어볼 필요가 있다.

지금까지 CATextLayer 에 대해 간략히 살펴봤다.

[관련글] CALayer 시작하기
[관련글] 스위프트(Swift) 가이드​

댓글 없음 :