代码基于Swift 4.0.
####一、坐标系
CoreText 的原点是左下角。 而进行UI布局时参照的坐标系原点在左上角。所以一般会对坐标系进行翻转。
在override func draw(_ rect: CGRect) 中调用
// coreText 设置前10个字为红色带下划线
func test01() {
// 1.
let context = UIGraphicsGetCurrentContext()
// 2. 由于CoreText一开始便是定位于桌面的排版系统,所以使用了传统的原点在左下角的坐标系,所以它在绘制文本的时候都是参照左下角的原点进行绘制的。
// 转换坐标为左上角
context?.textMatrix = CGAffineTransform.identity
context?.translateBy(x: 0, y: bounds.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
// 3.
let path = CGMutablePath()
path.addRect(bounds)
// 4
let string = "Hello CoreText! 由于CoreText一开始便是定位于桌面的排版系统,所以使用了传统的原点在左下角的坐标系,所以它在绘制文本的时候都是参照左下角的原点进行绘制的"
// let attrString = NSAttributedString(string:"Hello CoreText! 由于CoreText一开始便是定位于桌面的排版系统,所以使用了传统的原点在左下角的坐标系,所以它在绘制文本的时候都是参照左下角的原点进行绘制的")
var attributes = [NSAttributedString.Key: Any]()
attributes[NSAttributedString.Key.font] = UIFont.systemFont(ofSize: 15)
let mutableAttrString = NSMutableAttributedString(string: string, attributes: attributes)
mutableAttrString.addAttribute(.font, value: UIFont.systemFont(ofSize: 20), range: NSRange(location: 0, length: 10))
mutableAttrString.addAttribute(.foregroundColor, value: UIColor.red, range: NSRange(location: 0, length: 10))
mutableAttrString.addAttribute(.underlineStyle, value: NSNumber(value: 1), range: NSRange(location: 0, length: 10))
let framesetter = CTFramesetterCreateWithAttributedString(mutableAttrString)
let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, mutableAttrString.length), path, nil)
// 5
CTFrameDraw(frame,context!)