我想要一些具有自定义行距的文本,所以我使用 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];
但是行高没有变化。我想我在这里遗漏了一些东西,但我不知道是什么。
我尝试过使用 kCTParagraphStyleSpecifierLineSpacingAdjustment
和 kCTParagraphStyleSpecifierLineSpacing
但它们似乎都不起作用(?)。我还尝试使用 kCTParagraphStyleSpecifierAlignment
设置对齐(我知道 CATextLayer
有一个属性)只是为了测试 kCTParagraphStyleAttributeName
确实有效但它没有't.
我注意到即使我传递了一些疯狂的值(例如:CTParagraphStyleCreate(styleSettings, -555);
)这让我问自己:CATextLayer
支持段落属性吗?如果是这样,我在这里缺少什么?
最佳答案
我试过你的代码,将 NSAttributedString 放在 CATextLayer 中,它忽略了格式,正如你所说。
然后我尝试使用 CTFrameDraw
将完全相同的属性字符串绘制到 UIView drawRect
方法,并且它符合您的所有格式。我只能假设 CATextLayer 忽略了它的大部分格式。 CATextLayer Class Reference有许多关于它为了提高效率所做的事情的警告。
如果您确实需要绘制到 CALayer
,而不是 UIView
,您可以创建自己的 CALayer 子类或委托(delegate)并在那里进行绘制。
- (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);
}
关于objective-c - CATextLayer + NSAttributtedString + CTParagraphStyleRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10071198/