我希望我的文本被白色边框包围。我使用CATextLayer作为文本。我知道CATextLayer没有属性borderColor/borderWidth。当然,我可以使用它的超类(CALayer)的属性,但是它在层的框架周围绘制了一个边界,而不是文本本身。有人知道我如何使用CATextLayer实现这一点吗?

发布于 2012-01-03 17:29:41
以防有人对我的解决方案感兴趣:
基本上,可以在不直接使用CoreText的情况下制作带有笔划(边框)的文本。CATextLayer的string属性接受NSAttributedStrings。因此,只需在NSAttributedString的属性中指定笔划颜色和笔划宽度即可。
不幸的是,我需要对字体大小进行动画处理。string属性是可动画的,但前提是它是一个NSString。所以我决定将CATextLayer子类。经过多次尝试,我终于意识到CATextLayer的字符串和内容属性是互斥的,这意味着要么显示字符串,要么显示内容。我自己也想不出怎么画这根线。只有在更新内容时才会调用display和drawInContext:ctx方法,但我不知道必须调用什么才能更新字符串。
因此,我决定编写自己的CATextLayer类,将CALayer子类化。我创建了一个名为fontSize的动画属性。当此函数为动画时,将调用drawInContext:ctx方法。在drawInContext:ctx方法中,我使用CoreText创建了一个新字符串,并使用fontSize属性相应地更新了它的大小。
发布于 2014-04-26 10:33:36
对于任何对该解决方案感兴趣的人,无需担心字体大小的动画:
@import QuartzCore;
@import CoreText;
- (void)addTextLayer
{
NSDictionary* attributes = @{ NSFontAttributeName : [UIFont boldSystemFontOfSize:40.0],
(NSString*)kCTForegroundColorAttributeName: (id)[UIColor blackColor].CGColor,
(NSString*)kCTStrokeWidthAttributeName: @(-2.0),
(NSString*)kCTStrokeColorAttributeName: (id)[UIColor whiteColor].CGColor };
CATextLayer* textLayer = [CATextLayer layer];
textLayer.string = [[NSAttributedString alloc] initWithString:@"Hello World" attributes:attributes];
// Do the rest...
}https://stackoverflow.com/questions/8702740
复制相似问题