iOS 动画家族iOS开发iOS程序猿

CoreText使用学习

2017-06-03  本文已影响135人  神采飞扬_2015

CoreText 框架中最常用的几个类

CTFont
CTFontCollection
CTFontDescriptor
CTFrame
CTFramesetter
CTGlyphInfo
CTLine
CTParagraphStyle
CTRun
CTTextTab
CTTypesetter

CoreText坐标系

image

CoreText坐标系 和 UIKit坐标系 的不同,从图中可看出 CoreText坐标系是以左下角为坐标原点 ,而我们常使用的 UIKit是以左上角为坐标原点 ,因此在CoreText中的布局完成后需要对其坐标系进行转换,否则直接绘制出现位置反转的镜像情况。在通常情况下我们一般做法是直接获取当前上下文。并将当前上下文的坐标系转换为CoreText坐标系,再将布局好的CoreText绘制到当前上下文中即可。

// 获取当前上下文
CGContextRef context = UIGraphicsGetCurrentContext();

// 1.设置当前文本矩阵
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
// 2.文本沿y轴移动
CGContextTranslateCTM(context, 0, self.bounds.size.height);
// 3.文本翻转成为CoreText坐标系
CGContextScaleCTM(context, 1.0, -1.0);

绘制CoreText大致思路

整体视窗组合图 image
// 1.创建绘制区域,显示的区域可以用CGMUtablePathRef生成任意的形状
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(20, 50, self.bounds.size.width - 40, self.bounds.size.height - 100));   
// 2.创建需要绘制的文字
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:@"文本内容文本内容"];
// 3.根据AttString生成CTFramesetterRef
CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attString);
// 4.利用CTFramesetterRef得到CTFrame
CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, [attString length]), path, NULL);

字体基本知识

image image image image image

红框高度既为当前行的行高,绿线为baseline,绿色到红框上部分为当前行的最大Ascent,绿线到黄线为当前行的最大Desent,而黄框的高即为行间距。由此可以得出:lineHeight = Ascent + |Decent| + Leading(行间距)。

常用属性介绍

// 字体形状属性:必须是CFNumberRef对象默认为0,非0则对应相应的字符形状定义,如1表示传统字符形状
const CFStringRef kCTCharacterShapeAttributeName;              

// 字体属性:必须是CTFont对象
const CFStringRef kCTFontAttributeName;                        

// 字符间隔属性:必须是CFNumberRef对象
const CFStringRef kCTKernAttributeName;                        

// 设置是否使用连字属性:设置为0,表示不使用连字属性。标准的英文连字有FI,FL.默认值为1,既是使用标准连字。也就是当搜索到f时候,会把fl当成一个文字。必须是CFNumberRef 默认为1,可取0,1,2
const CFStringRef kCTLigatureAttributeName;                 

// 字体颜色属性:必须是CGColor对象,默认为black
const CFStringRef kCTForegroundColorAttributeName;             

 // 上下文的字体颜色属性:必须为CFBooleanRef 默认为False
const CFStringRef kCTForegroundColorFromContextAttributeName; 

 // 段落样式属性:必须是CTParagraphStyle对象 默认为NIL
const CFStringRef kCTParagraphStyleAttributeName;              

// 笔画线条宽度:必须是CFNumberRef对象,默为0.0f,标准为3.0f
const CFStringRef kCTStrokeWidthAttributeName;              

// 笔画的颜色属性:必须是CGColorRef 对象,默认为前景色
const CFStringRef kCTStrokeColorAttributeName;              

// 设置字体的上下标属性:必须是CFNumberRef对象 默认为0,可为-1为下标,1为上标,需要字体支持才行。如排列组合的样式Cn1
const CFStringRef kCTSuperscriptAttributeName;              

// 字体下划线颜色属性:必须是CGColorRef对象,默认为前景色
const CFStringRef kCTUnderlineColorAttributeName;           

// 字体下划线样式属性:必须是CFNumberRef对象,默为kCTUnderlineStyleNone 可以通过CTUnderlineStypleModifiers 进行修改下划线风格
const CFStringRef kCTUnderlineStyleAttributeName;           

// 文字的字形方向属性:必须是CFBooleanRef 默认为false,false表示水平方向,true表示竖直方向
const CFStringRef kCTVerticalFormsAttributeName;

// 字体信息属性:必须是CTGlyphInfo对象
const CFStringRef kCTGlyphInfoAttributeName;

// CTRun 委托属性:必须是CTRunDelegate对象
const CFStringRef kCTRunDelegateAttributeName

文本属性设置:

// 设置绘制的文本内容
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:@"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"];

// 设置文本内容的属性
// 1.设置部分文字颜色
[attString addAttribute:(id)kCTForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0 , 27)];

// 2.设置部分文字字体
CGFloat fontSize = 20;
CTFontRef fontRef = CTFontCreateWithName((CFStringRef)@"ArialMT", fontSize, NULL);
[attString addAttribute:(id)kCTFontAttributeName value:(__bridge id)fontRef range:NSMakeRange(0, 27)];

// 3.设置斜体
CTFontRef italicFontRef = CTFontCreateWithName((CFStringRef)[UIFont italicSystemFontOfSize:20].fontName, 16, NULL);
[attString addAttribute:(id)kCTFontAttributeName value:(__bridge id)italicFontRef range:NSMakeRange(27, 9)];

// 4.设置下划线
[attString addAttribute:(id)kCTUnderlineStyleAttributeName value:(id)[NSNumber numberWithInteger:kCTUnderlineStyleDouble] range:NSMakeRange(36, 10)];

// 5.设置下划线颜色
[attString addAttribute:(id)kCTUnderlineColorAttributeName value:(id)[UIColor greenColor].CGColor range:NSMakeRange(36, 10)];

// 6.设置空心字
long number1 = 2;
CFNumberRef numRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt8Type, &number1);
[attString addAttribute:(id)kCTStrokeWidthAttributeName value:(__bridge id)numRef range:NSMakeRange(56, 10)];

// 7.设置字体间距
long number = 10;
CFNumberRef num = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt8Type, &number);
[attString addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(40, 10)];

// 8.设置行间距
CGFloat lineSpacing = 10;
const CFIndex kNumberOfSettings = 3;
CTParagraphStyleSetting theSettings[kNumberOfSettings] = {
    {kCTParagraphStyleSpecifierLineSpacingAdjustment, sizeof(CGFloat), &lineSpacing},
    {kCTParagraphStyleSpecifierMaximumLineHeight, sizeof(CGFloat), &lineSpacing},
    {kCTParagraphStyleSpecifierMinimumLineHeight, sizeof(CGFloat), &lineSpacing}
    };
CTParagraphStyleRef theParagraphRef = CTParagraphStyleCreate(theSettings, kNumberOfSettings);
[attString addAttribute:(id)kCTParagraphStyleAttributeName value:(__bridge id)theParagraphRef range:NSMakeRange(0, [attString length])];

绘制图片

Core Text本身并不支持图片绘制,图片的绘制你还得通过Core Graphics来进行。Core Text可以通过CTRun的设置为你的图片在文本绘制的过程中留出适当的空间。这个设置就使用到CTRunDelegate。CTRunDelegate作为CTRun相关属性或操作扩展的一个入口,使得我们可以对CTRun做一些自定义的行为。为图片留位置的方法就是加入一个空白的CTRun,自定义其ascent,descent,width等参数,使得绘制文本的时候留下空白位置给相应的图片。然后图片在相应的空白位置上使用Core Graphics接口进行绘制。

图片宽高需要加载后才知道,而在文本绘制中需要直接留出其位置再进行绘制,所以图片的宽高都是在数据中保存好的。为了留出其位置我们需要用空白的字符来做占位符使用。为了知道其图片绘制的位置(即空白占位符位置)我们需要设置代理才能够得知图片绘制位置。

使用CTRunDelegateCreate可以创建一个CTRunDelegate,它接收两个参数,一个是callbacks结构体,一个是所有callback调用的时候需要传入的对象。 callbacks的结构体为CTRunDelegateCallbacks,主要是包含一些回调函数,比如有返回当前run的ascent,descent,width这些值的回调函数,至于函数中如何鉴别当前是哪个run,可以在CTRunDelegateCreate的第二个参数来达到目的,因为CTRunDelegateCreate的第二个参数会作为每一个回调调用时的入参。

具体实现:

#pragma mark - CTRunDelegateCallbacks Method
static CGFloat ascentCallback(void *ref) {
    return [(NSNumber *)[(__bridge NSDictionary *)ref objectForKey:@"height"] floatValue];
}

static CGFloat descentCallback(void *ref) {
    return 0;
}

static CGFloat widthCallback(void *ref) {
    return [(NSNumber *)[(__bridge NSDictionary *)ref objectForKey:@"width"] floatValue];
}

#pragma mark - 空白占位符及代理设置
+ (NSAttributedString *)parseImageDataFromNSDictionary:(NSDictionary *)dict config:(CTFrameParserConfig *)config {
    // CTRunDelegateCallBacks:用于保存指针的结构体,由CTRun delegate进行回调
    CTRunDelegateCallbacks callbacks;
    memset(&callbacks, 0, sizeof(CTRunDelegateCallbacks));
    callbacks.version = kCTRunDelegateVersion1;
    callbacks.getAscent = ascentCallback;
    callbacks.getDescent = descentCallback;
    callbacks.getWidth = widthCallback;
    // 字典中含有图片的宽高信息
    // 创建CTRunDelegate的代理
    CTRunDelegateRef delegate = CTRunDelegateCreate(&callbacks, (__bridge void *)(dict));

    // 使用0xFFFC作为空白的占位符
    unichar objectReplacementChar = 0xFFFC;
    NSString *content = [NSString stringWithCharacters:&objectReplacementChar length:1];
    NSDictionary *attributes = [self attributesWithConfig:config];
    NSMutableAttributedString *space = [[NSMutableAttributedString alloc] initWithString:content attributes:attributes];
    // 设置代理
    CFAttributedStringSetAttribute((CFMutableAttributedStringRef)space, CFRangeMake(0, 1), kCTRunDelegateAttributeName, delegate);
    CFRelease(delegate);

    return space;
}

#pragma mark - drawRect
- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    if (self.data == nil) {
        return;
    }

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    if (self.state == CTDisplayViewStateTouching || self.state == CTDisplayViewStateSelecting) {
        [self drawSelectionArea];
        [self drawAnchors];
    }

    CTFrameDraw(self.data.ctFrame, context);

    // 遍历图片数组,在适当的位置插入绘制的图片
    for (CTImageData *imageData in self.data.imageArray) {
        UIImage *image = [UIImage imageNamed:imageData.name];
        if (image) {
            CGContextDrawImage(context, imageData.imagePosition, image.CGImage);
        }
    }
}

CTRun delegate进行回调:

- (void)fillImagePosition {
    if (self.imageArray.count == 0) {
        return;
    }
    
    // 获取CTLine数组
    NSArray *lines = (NSArray *)CTFrameGetLines(self.ctFrame);
    NSUInteger lineCount = [lines count];
    CGPoint lineOrigins[lineCount];
    CTFrameGetLineOrigins(self.ctFrame, CFRangeMake(0, 0), lineOrigins);

    int imgIndex = 0;
    CTImageData *imageData = self.imageArray[0];

    //遍历CTline
    for (int i = 0; i < lineCount; ++i) {
        if (imageData == nil) {
            break;
        }
        CTLineRef line = (__bridge CTLineRef)lines[i];
        NSArray *runObjArray = (NSArray *)CTLineGetGlyphRuns(line);
        // 遍历每个CTLine中的CTRun找到空白字符的delegate
        for (id runObj in runObjArray) {
            CTRunRef run = (__bridge CTRunRef)runObj;
            NSDictionary *runAttributes = (NSDictionary *)CTRunGetAttributes(run);
            CTRunDelegateRef delegate = (__bridge CTRunDelegateRef)[runAttributes valueForKey:(id)kCTRunDelegateAttributeName];
            if (delegate == nil) {
                continue;
            }

            NSDictionary *metaDic = CTRunDelegateGetRefCon(delegate);
            if (![metaDic isKindOfClass:[NSDictionary class]]) {
                continue;
            }
            
            // 找到代理后开始计算空白字符的位置
            CGRect runBounds;
            CGFloat ascent;
            CGFloat descent;
            runBounds.size.width = CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, &descent, NULL);
            runBounds.size.height = ascent + descent;
            
            // 计算在行当中的x偏移量
            CGFloat xOffset = CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).location, NULL);
            runBounds.origin.x = lineOrigins[i].x + xOffset;
            runBounds.origin.y = lineOrigins[i].y;
            runBounds.origin.y -= descent;
            
            // 获得ctframe的绘制区域
            CGPathRef pathRef = CTFrameGetPath(self.ctFrame);
            // 计算此绘制区域的范围
            CGRect colRect = CGPathGetBoundingBox(pathRef);

            // 计算在此区域中空白字符的位置
            CGRect delegateBounds = CGRectOffset(runBounds, colRect.origin.x, colRect.origin.y);

            // 记录空白字符位置
            imageData.imagePosition = delegateBounds;
            imgIndex++;
            if (imgIndex == self.imageArray.count) {
                imageData = nil;
                break;
            } else {
                imageData = self.imageArray[imgIndex];
            }
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读