[swift] Core Text 프레임워크를 사용한 텍스트 레이아웃 및 서식 설정 방법

Core Text는 iOS 및 macOS에서 고급 텍스트 레이아웃 및 서식 설정을 제공하는 프레임워크입니다. 이 프레임워크를 사용하면 텍스트의 높은 품질과 다양한 서식을 지원하는 데 있어 많은 유연성을 가질 수 있습니다.

이제 Core Text를 사용하여 텍스트의 레이아웃 및 서식을 설정하는 방법에 대해 알아보겠습니다.

1. NSAttributedString 생성하기

NSAttributedString은 텍스트와 해당 서식 정보를 결합하는 데 사용됩니다. 서식을 적용할 문자열과 서식 정보를 포함하는 NSAttributedString 객체를 생성합니다.

이미 문자열이 있을 경우:

let myString = "Core Text 사용하기"
let attributes: [NSAttributedString.Key: Any] = [
    .font: UIFont(name: "Helvetica", size: 24.0),
    .foregroundColor: UIColor.red
]
let attributedString = NSAttributedString(string: myString, attributes: attributes)

2. Core Text 객체 초기화

Core Text에서 사용되는 텍스트 레이아웃 및 서식 설정 객체를 초기화합니다.

let framesetter = CTFramesetterCreateWithAttributedString(attributedString)
let framePath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 200, height: 200))
let frameRef = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attributedString.length), framePath.cgPath, nil)

3. 그리기

준비가 완료되면 다음 단계는 생성한 텍스트 프레임을 화면에 그리는 것입니다.

let context = UIGraphicsGetCurrentContext()
context?.textMatrix = CGAffineTransform.identity
context?.translateBy(x: 0, y: 200)
context?.scaleBy(x: 1.0, y: -1.0)
CTFrameDraw(frameRef, context!)

Core Text를 사용하여 텍스트 레이아웃과 서식을 설정하는 방법에 대해 간략하게 살펴보았습니다. Core Text에는 더 많은 기능과 옵션이 있으며, 이를 통해 더욱 정교한 텍스트 레이아웃 및 서식을 적용할 수 있습니다.

더 자세한 내용은 Apple 개발자 문서를 참고하시기 바랍니다.

Core Text 프레임워크 - Apple 개발자 문서