CoreText的认识(一)

整理下最近关于学习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!)
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Core Text is an advanced, low-level technology for laying...
    forping阅读 5,979评论 0 3
  • CoreText是一个进阶的比较底层的布局文本和处理字体的技术,CoreText API在OS X v10.5 和...
    smalldu阅读 14,649评论 18 129
  • 苹果文档 https://developer.apple.com/documentation/coretext C...
    阳明AI阅读 3,237评论 0 4
  • iOS没有现成的支持图文混排的控件,而要用多个基础控件组合拼成图文混排这样复杂的排版,是件很苦逼的事情。对此的解决...
    清风沐沐阅读 3,916评论 0 2
  • 很久以前写的文章搬到这里来放着。iOS开发中经常会遇到做一些文字排版的需求,文字图片混排的需求,在iOS7 以前一...
    AlienJunX阅读 3,811评论 0 2

友情链接更多精彩内容