3

我有以下代码在矩形中绘制属性字符串:

CGContextRef context = UIGraphicsGetCurrentContext();
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)string);

    // left column form
    CGMutablePathRef leftColumnPath = CGPathCreateMutable();
    CGPathAddRect(leftColumnPath, NULL, CGRectMake(rect.origin.x, -rect.origin.y,rect.size.width, self.bounds.size.height));

    // left column frame
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);   
    CTFrameRef leftFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), leftColumnPath, NULL);
    CTFrameDraw(leftFrame, context);

这里一切正常,但我需要更好地控制每一行。因此,我不想绘制框架,而是分别绘制每条线。所以我尝试使用 CTFrameDraw 来代替:

CFArrayRef linesArray =  CTFrameGetLines(leftFrame);
    for (CFIndex i = 0; i < CFArrayGetCount(linesArray); i++){
        CTLineRef line = CFArrayGetValueAtIndex(linesArray, i);
        CTLineDraw(line, context);
}

但是,这与绘制框架的结果不同。我是 Core Text 的新手,所以我还应该做更多的事情来划清界限吗?当前这个循环执行了几次,但是屏幕底部只画了一条线(而不是用 CTFrameDraw 在顶部)

4

2 回答 2

2

CGContextSetTextPosition(context, x, y)在之前插入CTLineDraw并根据需要更改 x 和 y(不要忘记y反转)

于 2012-05-14T02:14:26.163 回答
1

示例代码摘自: https ://github.com/BigZaphod/Chameleon/blob/master/UIKit/Classes/UIStringDrawing.m

 if (lines)
 {
     CFIndex numberOfLines = CFArrayGetCount(lines);

    numberOfLines = 3;

    const CGFloat fontLineHeight = font.lineHeight;
    CGFloat textOffset = 0;

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSaveGState(ctx);
    CGContextTranslateCTM(ctx, rect.origin.x, rect.origin.y+font.ascender);
    CGContextSetTextMatrix(ctx, CGAffineTransformMakeScale(1,-1));

    for (CFIndex lineNumber=0; lineNumber<numberOfLines; lineNumber++) {
        CTLineRef line = CFArrayGetValueAtIndex(lines, lineNumber);
        float flush = 0.5;

        switch (alignment) {
            case UITextAlignmentCenter: flush = 0.5;    break;
            case UITextAlignmentRight:  flush = 1;      break;
            case UITextAlignmentLeft:
            default:                    flush = 0;      break;
        }

        CGFloat penOffset = CTLineGetPenOffsetForFlush(line, flush, rect.size.width);
        CGContextSetTextPosition(ctx, penOffset, textOffset);
        CTLineDraw(line, ctx);
        textOffset += fontLineHeight;
    }

    CGContextRestoreGState(ctx);

    CFRelease(lines);
}
于 2012-07-09T09:26:04.337 回答