2012-01-02 51 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... 
}