【问题标题】:CATextLayer font borderColor?CATextLayer 字体边框颜色?
【发布时间】:2012-01-31 22:19:42
【问题描述】:

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

【问题讨论】:

  • 某事告诉我,这样做的唯一方法是继承 CATextLayer 或使用委托方法 drawLayer:inContext: 自己进行实际绘图。
  • 感谢您的评论。听起来很难实施。我想知道我会自己画……
  • low-level text rendering 上查看此页面。起初它相当大,但花点时间处理它,你就会明白发生了什么。
  • @pe8ter:非常感谢那个链接。它帮助我意识到我需要使用 CoreText 框架来实现这一点。

标签: iphone objective-c ios ipad calayer


【解决方案1】:

以防万一有人对我的解决方案感兴趣:

基本上可以不直接使用 CoreText 来制作带有笔划(边框)的文本。 CATextLayer 的字符串属性接受 NSAttributedStrings。因此,它就像在其属性中提供带有笔触颜色和笔触宽度的 NSAttributedString 一样简单。

不幸的是,我需要为字体大小设置动画。 string 属性是可动画的,但前提是它是 NSString。所以我决定继承 CATextLayer。经过多次尝试,我意识到 CATextLayer 的字符串和内容属性是互斥的,这意味着要么显示字符串,要么显示内容。我无法弄清楚如何自己绘制字符串。只有在更新内容时才会调用 display 和 drawInContext:ctx 方法,但我不知道要调用什么来更新字符串。

所以我决定编写自己的 CATextLayer 类,继承 CALayer。我创建了一个名为 fontSize 的动画属性。当这个动画时,drawInContext:ctx 方法被调用。在 drawInContext:ctx 方法中,我使用 CoreText 创建一个新字符串,并使用 fontSize 属性相应地更新其大小。

【讨论】:

    【解决方案2】:

    对于任何对解决方案感兴趣而无需担心字体大小动画的人:

    @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...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-24
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多