我想要一些具有自定义行距的文本,所以我用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确实可以工作,但它没有。
我注意到,即使我传递了一些疯狂的值(例如:CTParagraphStyleCreate(styleSettings, -555);),这也导致我问自己:CATextLayer是否支持段落属性?如果是这样,我在这里遗漏了什么?
发布于 2012-04-09 20:55:01
我试过您的代码,将NSAttributedString放在一个CATextLayer中,它忽略了格式,正如您所说的那样。
然后,我尝试使用CTFrameDraw将完全相同的属性字符串绘制到UIView drawRect方法,它遵循您的所有格式。我只能假设CATextLayer忽略了它的大部分格式。CATextLayer Class Reference对它为了提高效率所做的事情提出了许多警告。
如果您确实需要绘制到CALayer,而不是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);
}https://stackoverflow.com/questions/10071198
复制相似问题