2012-01-02 52 views
4

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

enter image description here

+0

有什么地方告诉我,这样做的唯一办法是,要么子类'CATextLayer'或使用委托方法'drawLayer :inContext:'自己做实际的绘图。 – 2012-01-02 15:54:07

+0

感谢您的评论。这听起来很难实施。我不知道我会自己做图... – strave 2012-01-02 16:05:08

+0

看看[低级文字渲染](http://www.codeproject.com/KB/iPhone/Glyph.aspx)上的这个页面。它起初相当大,但花时间处理它,你会得到正在发生的事情的要点。 – pe8ter 2012-01-03 06:35:05

回答

5

万一有人愿意在我的解决方案:

基本上它有可能使一个行程(境)文本不直接使用CoreText。 CATextLayer的字符串属性接受NSAttributedStrings。因此,就像在属性中给一个NSAttributedString使用笔触颜色和笔触宽度一样简单。

不幸的是我需要动画字体大小。字符串属性是可以动画的,但只有当它是一个NSString。所以我决定继承CATextLayer。经过大量尝试后,我意识到CATextLayer的字符串和内容属性是相互排斥的,也就是说,字符串或内容都显示出来。我无法弄清楚如何自己绘制字符串。 display和drawInContext:ctx方法仅在内容更新时才被调用,但我不知道为了更新字符串我需要调用什么。

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

3

任何有兴趣的解决方案,而无需担心动画字体大小:

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