整理下最近關(guān)于學習CoreText的認識和理解
1.關(guān)于坐標系
CoreText坐標系和UIKit坐標系是不一樣的栽惶,UIKit坐標系是以左上角為原點迅脐,而CoreText坐標系是以左下角為原點的芍殖。
所以,我們在CoreText布局完成后要對坐標系進行轉(zhuǎn)換谴蔑。
override func draw(_ rect: CGRect) {
super.draw(rect)
// 1. 獲取上下文
let context = UIGraphicsGetCurrentContext()
// 2. 翻轉(zhuǎn)坐標
context?.textMatrix = .identity
context?.translateBy(x: 0, y: self.bounds.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
}
2.CoreText布局步驟
- 1.首先要確定布局時繪制的區(qū)域豌骏;
- 2.設(shè)置文本內(nèi)容;
- 3.生成CTFramesetter隐锭;
- 4.生成CTFrame窃躲;
- 5.CTFrameDraw繪制;
override func draw(_ rect: CGRect) {
super.draw(rect)
let context = UIGraphicsGetCurrentContext()
context?.textMatrix = .identity
context?.translateBy(x: 0, y: self.bounds.height)
context?.scaleBy(x: 1.0, y: -1.0)
let path = UIBezierPath(rect: self.bounds)
let attributeString = NSMutableAttributedString(string: "aaaaaaaaaaaaaaaaa")
attributeString.addAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.blue], range: NSRange(location: 0, length: attributeString.length))
let framesetter = CTFramesetterCreateWithAttributedString(attributeString)
let ctframe = CTFramesetterCreateFrame(framesetter, CFRange(location: 0, length: attributeString.length), path.cgPath, nil)
CTFrameDraw(ctframe, context!)
}