5

我想要一些带有自定义行距的文本,所以我写了一个属性字符串CTParagraphStyleAttributte并将其传递给我的CATextLayer

UIFont *font = [UIFont systemFontOfSize:20];
CTFontRef ctFont = CTFontCreateWithName((CFStringRef)font.fontName,
                                        font.pointSize, NULL);
CGColorRef cgColor = [UIColor whiteColor].CGColor;
CGFloat leading = 25.0;
CTTextAlignment alignment = kCTRightTextAlignment; // just for test purposes
const CTParagraphStyleSetting styleSettings[] = {
    {kCTParagraphStyleSpecifierLineSpacingAdjustment, sizeof(CGFloat), &leading},
    {kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment), &alignment}
};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(styleSettings, 2));
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                            (id)ctFont, (id)kCTFontAttributeName,
                            (id)cgColor, (id)kCTForegroundColorAttributeName,
                            (id)paragraphStyle, (id)kCTParagraphStyleAttributeName,
                            nil];
CFRelease(ctFont);
CFRelease(paragraphStyle);

NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] 
                                                 initWithString:string
                                                     attributes:attributes];
_textLayer.string = attrStr;
[attrStr release];

但是行高没有改变。我想我在这里遗漏了一些东西,但我不知道是什么。

我已经尝试过kCTParagraphStyleSpecifierLineSpacingAdjustmentkCTParagraphStyleSpecifierLineSpacing但它们中的任何一个似乎都不起作用(?)。我还尝试使用kCTParagraphStyleSpecifierAlignment(我知道CATextLayer有一个属性)来设置对齐方式,只是为了测试kCTParagraphStyleAttributeName确实有效,但它没有。

我注意到即使我传递了一些疯狂的值(例如:)CTParagraphStyleCreate(styleSettings, -555);,这也会让我问自己:是否CATextLayer支持段落属性?如果是这样,我在这里错过了什么?

4

1 回答 1

3

我试过你的代码,将 NSAttributedString 放在 CATextLayer 中,它忽略了格式,如你所说。

然后我尝试使用 UIView 方法将完全相同的属性字符串绘制到 UIViewdrawRect方法中CTFrameDraw,它遵循了您的所有格式。我只能假设 CATextLayer 忽略了它的大部分格式。CATextLayer类参考有许多关于它为了提高效率所做的事情的警告。

如果您真的需要绘制到 a CALayer,而不是 a UIView,您可以创建自己的 CALayer 子类或委托并在那里进行绘图。

- (void)drawRect:(CGRect)rect
{
    //
    // Build attrStr as before.
    //

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect bounds = [self bounds];

    // Text ends up drawn inverted, so we have to reverse it.
    CGContextSetTextMatrix(ctx, CGAffineTransformIdentity);
    CGContextTranslateCTM( ctx, bounds.origin.x, bounds.origin.y+bounds.size.height );
    CGContextScaleCTM( ctx, 1, -1 );

    // Build a rectangle for drawing in.
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, bounds);

    // Create the frame and draw it into the graphics context
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef) attrStr);
    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
    CFRelease(framesetter);
    CFRelease(path);

    // Finally do the drawing.
    CTFrameDraw(frame, ctx);
    CFRelease(frame);          
}
于 2012-04-09T12:55:00.817 回答