原文
https://blog.changyy.org/2014/06/ios-core-text-paragraphs-lines-glyph.html
image.pngCore Text is an advanced, low-level technology for laying out text and handling fonts. The Core Text API, introduced in Mac OS X v10.5 and iOS 3.2, is accessible from all OS X and iOS environments.
先搞懂String 在iOS 系统内是如何被画到UIView 上头:
CTFramesetter -> CTFrame (paragraphs) -> CTLine (lines) -> CTRun (glyph runs)
简易的范例: 结果: 其中每一个run 代表同一个attributed string ,此例数字、中文交替,所以共有6 个run。另一个例子: 由于有两个"我"在同一个run 中,所以只有6 个run。
NSString *utf8String = @"0你1我2他";
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:utf8String];
CTLineRef line = CTLineCreateWithAttributedString((CFMutableAttributedStringRef) attrString);
CFIndex glyphLength = CTLineGetGlyphCount(line);
CFArrayRef runArray = CTLineGetGlyphRuns(line);
CFIndex runArrayLength = CFArrayGetCount(runArray);
for (CFIndex runIndex = 0; runIndex < runArrayLength; runIndex++) {
CTRunRef run = (CTRunRef) CFArrayGetValueAtIndex(runArray, runIndex);
CTFontRef runFont = CFDictionaryGetValue(CTRunGetAttributes(run), kCTFontAttributeName);
for (CFIndex runGlyphIndex = 0; runGlyphIndex < CTRunGetGlyphCount(run); runGlyphIndex++) {
CFRange thisGlyphRange = CFRangeMake(runGlyphIndex, 1);
CGGlyph glyph;
CGPoint position;
CTRunGetGlyphs(run, thisGlyphRange, &glyph);
CTRunGetPositions(run, thisGlyphRange, &position);
//CGContextShowGlyphsAtPositions(context, &glyph, &position, 1);
}
}
NSLog(@"intput: %lu, runArrayLength: %@, glyphLength:%@", [utf8String length], @(runArrayLength), @(glyphLength));
intput: 6, runArrayLength: 6, glyphLength:6
NSString *utf8String = @"0你1我我2他";
intput: 7, runArrayLength: 6, glyphLength:7
网友评论