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)簡易的範例:
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
其中每一個 run 代表同一個 attributed string ,此例數字、中文交替,所以共有 6 個 run。另一個例子:
NSString *utf8String = @"0你1我我2他";
intput: 7, runArrayLength: 6, glyphLength:7
由於有兩個"我"在同一個 run 中,所以只有 6 個 run。
沒有留言:
張貼留言