CoreText的认识(一)
2018-12-18 本文已影响0人
向日葵的夏天_summer
整理下最近关于学习CoreText的认识和理解
1.关于坐标系
CoreText坐标系和UIKit坐标系是不一样的,UIKit坐标系是以左上角为原点,而CoreText坐标系是以左下角为原点的。
所以,我们在CoreText布局完成后要对坐标系进行转换。
override func draw(_ rect: CGRect) {
super.draw(rect)
// 1. 获取上下文
let context = UIGraphicsGetCurrentContext()
// 2. 翻转坐标
context?.textMatrix = .identity
context?.translateBy(x: 0, y: self.bounds.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
}
2.CoreText布局步骤
- 1.首先要确定布局时绘制的区域;
- 2.设置文本内容;
- 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!)
}