CoreText 学习记录

代码基于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!)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值