CTFrameGetLineOrigins为单行文本获取不正确的起源Y.

时间:2014-01-30 14:54:22

标签: ios iphone core-text

CTFrameGetLineOrigins的奇怪行为:

  1. 如果我有多行文字 - 它会返回Y的正确值;
  2. 如果只有一行文字,则返回错误的值。
  3. 这是一个错误还是我错过了什么?

    正确的结果:

    line:         0
    self height:  48.000000
    origins y:    35.000000
    ascent:       13.328000
    descent:      3.374000
    

    结果不正确:

    line:         0
    self height:  16.000000
    origins y:    15.000000
    ascent:       13.328000
    descent:      3.374000
    

    代码:

    CGRect textRect = [self textRectForBounds:self.bounds limitedToNumberOfLines:self.numberOfLines];
    
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, textRect);
    CTFrameRef frame = CTFramesetterCreateFrame([self framesetter], CFRangeMake(0, (CFIndex)[self.attributedText length]), path, NULL);
    if (frame == NULL) {
        CFRelease(path);
        return nil;
    }
    
    NSArray* lines = (NSArray*)CTFrameGetLines(frame);
    CFIndex lineCount = [lines count];
    
    CGPoint origins[lineCount];
    CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), origins);
    
    for(CFIndex idx = 0; idx < lineCount; idx++)
    {
        NSLog(@"origin %d: x=%f, y=%f", (int)idx, origins[idx].x, origins[idx].y);
    
        CTLineRef line = CFArrayGetValueAtIndex((CFArrayRef)lines, idx);
    
        CFArrayRef glyphRuns = CTLineGetGlyphRuns(line);
        CFIndex glyphCount = CFArrayGetCount(glyphRuns);
        for (int i = 0; i < glyphCount; ++i)    {
            CTRunRef run = CFArrayGetValueAtIndex(glyphRuns, i);
            CGRect runBounds;
    
            CGFloat ascent;
            CGFloat descent;
            runBounds.size.width = CTRunGetTypographicBounds(run, CFRangeMake(0, 0), &ascent, &descent, NULL);
            runBounds.size.height = ascent + descent;
    
            runBounds.origin.x = CTLineGetOffsetForStringIndex(line, CTRunGetStringRange(run).location, NULL);
            runBounds.origin.y = self.frame.size.height - origins[idx].y - ascent;
            NSLog(@"\n\
                  line:             %d\n\
                  self height:      %f\n\
                  origins y:        %f\n\
                  ascent:           %f\n\
                  descent:          %f", (int)idx, self.frame.size.height, origins[idx].y, ascent, descent);
        }
    }
    

0 个答案:

没有答案