初探Core Text 架构:paragraphs, lines, glyph runs and glyph

原文

https://blog.changyy.org/2014/06/ios-core-text-paragraphs-lines-glyph.html

image.png

Core 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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容