美文网首页
Core Text 系列1 - 初探

Core Text 系列1 - 初探

作者: 离子来了 | 来源:发表于2016-05-11 22:09 被阅读141次

Core Text

iOS图文混排的机制

步骤如下:

1.获取绘制上下文

 UIGraphicsGetCurrentContext() 
 UIGraphicsBeginImageContextWithOptions(self.bounds.size, true,  UIScreen.mainScreen().scale)

2.坐标系的转换

//坐标系转换
CGContextSetTextMatrix(ctx, CGAffineTransformIdentity)
CGContextTranslateCTM(ctx, 0, self.bounds.size.height)
CGContextScaleCTM(ctx, 1.0, -1.0)

3.创建绘制区域

let path = CGPathCreateMutable()
CGPathAddRect(path, nil, self.bounds)

4.创建属性字符串

let attributed =  NSMutableAttributedString(string: "😢我是属性字符串");
、、、在此添加属性

5.绘制

 //创建CTFramesetter
  let ctFrameSetter = CTFramesetterCreateWithAttributedString(attributed)
        
 //创建CTFrame
let ctFrame = CTFramesetterCreateFrame(ctFrameSetter, CFRangeMake(0, attributed.length),path , nil)
        
 //根据CTFrame绘制
 CTFrameDraw(ctFrame, ctx)

eg:CoreTextLayer.swft

 override func display() {
        self.contentsScale = UIScreen.mainScreen().scale
        super.display()
    }
    override func drawInContext(ctx: CGContext) {
        super.drawInContext(ctx)
       
        //坐标系转换
        CGContextSetTextMatrix(ctx, CGAffineTransformIdentity)
        CGContextTranslateCTM(ctx, 0, self.bounds.size.height)
        CGContextScaleCTM(ctx, 1.0, -1.0)
        
        //创建绘制的区域
        let path = CGPathCreateMutable()
        CGPathAddRect(path, nil, self.bounds)
        
        // 4.创建需要绘制的文字
        let attributed =  NSMutableAttributedString(string: "估后共和国开不开vbdkaph估后共和国开不开vbdkaph😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️😢😊😊😢⬇️这,我是要给兵个😢😊😊😢⬇️");
        
        attributed.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(20), range: NSMakeRange(0, 5));
        
        attributed.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(3, 10));
        
        attributed.addAttribute(NSForegroundColorAttributeName, value: UIColor.orangeColor(), range: NSMakeRange(0, 2));
        
        //创建段落属性
       let paraStyle = NSMutableParagraphStyle()
        
        attributed.addAttribute(NSParagraphStyleAttributeName, value: paraStyle, range: NSMakeRange(0, attributed.length))
        
        //创建CTFramesetter
       let ctFrameSetter = CTFramesetterCreateWithAttributedString(attributed)
        
        //创建CTFrame
       let ctFrame = CTFramesetterCreateFrame(ctFrameSetter, CFRangeMake(0, attributed.length),path , nil)
        
        //根据CTFrame绘制
       CTFrameDraw(ctFrame, ctx)
 
    }

相关文章

网友评论

      本文标题:Core Text 系列1 - 初探

      本文链接:https://www.haomeiwen.com/subject/csvurttx.html