CoreText简单使用

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

一、简介

先看看里面有什么

#include 
#include //字体
#include 
#include 
#include 
#include 
#include //位置
#include //大小
#include //图形
#include //行
#include //段落
#include 
#include //着重讲下
#include 
#include //属性文本
#include 
#include 
#include 
#include 

//版本说明
uint32_t CTGetCoreTextVersion( void ) CT_AVAILABLE(10_5, 3_2);

#define kCTVersionNumber10_5 0x00020000
#define kCTVersionNumber10_5_2 0x00020001
#define kCTVersionNumber10_5_3 0x00020002
#define kCTVersionNumber10_5_5 0x00020003
#define kCTVersionNumber10_6 0x00030000
#define kCTVersionNumber10_7 0x00040000
#define kCTVersionNumber10_8 0x00050000
#define kCTVersionNumber10_9 0x00060000
#define kCTVersionNumber10_10 0x00070000
#define kCTVersionNumber10_11 0x00080000

其实富文本是绘制出来的流程如下:

CoreText简单使用_第1张图片

而CTRun可以这样理解。如下:

哈哈哈 哈哈哈 哈哈哈 哈哈哈,这个几个字体样式各不相同,而每一个块相同的都是有一个CTRun来管理。

所以绘制流程结合上图

1.设置文本属性

2.属性转换成需要绘制的内容

3.绘制路径

子类化一个View

MyLablel.h

#import 

@interface MyLabel : UIView
@property (nonatomic, copy)NSString * text;
@end

MyLabel.m

#import "MyLabel.h"
#import 

@implementation MyLabel



- (void)drawRect:(CGRect)rect {
    NSMutableAttributedString * attributeString = [[NSMutableAttributedString alloc]initWithString:self.text];
    //添加属性
    NSDictionary * attDic1 = @{NSFontAttributeName : [UIFont systemFontOfSize:30],
                               NSForegroundColorAttributeName :[UIColor greenColor]
                               };
    NSDictionary * attDic2 = @{NSFontAttributeName : [UIFont systemFontOfSize:20],
                               NSForegroundColorAttributeName :[UIColor yellowColor]
                               };
    //把设置好的属性加到文本属性内
    //range表示从第几个字符开始的到第几个
    [attributeString addAttributes:attDic1 range:NSMakeRange(0, 4)];
    [attributeString addAttributes:attDic2 range:NSMakeRange(4,self.text.length-4)];
    //设置要绘制的内容 释放
    CTFramesetterRef framsestter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attributeString);//需要强转下
    
    //绘制路径 创建路径请求了 Path记得释放
    CGMutablePathRef path = CGPathCreateMutable();
    CGRect bounds = self.bounds;
    CGPathAddRect(path, NULL, bounds);
    
    //转换成要绘制的内容 释放
    CTFrameRef frame = CTFramesetterCreateFrame(framsestter, CFRangeMake(0, 0), path, NULL);
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    //坐标转换 不然会是倒着的
    CGContextTranslateCTM(ctx, 0, self.bounds.size.height);
    CGContextScaleCTM(ctx, 1, -1);
    
    //绘制出来
    CTFrameDraw(frame, ctx);
    
    //注意这些都市C语言要注意千万不能忘记内存管理,穿件都是需要释放
    CFRelease(framsestter);
    CFRelease(frame);
    CGPathRelease(path);

}

ViewController.m

MyLabel * mylabel = [[MyLabel alloc]initWithFrame:self.view.frame];
    mylabel.text = @"我是富文本啊 富文本";
    [self.view addSubview:mylabel];

CoreText简单使用_第2张图片

转载于:https://my.oschina.net/langzhouzhou1/blog/636306

你可能感兴趣的:(CoreText简单使用)