2013-05-09 69 views
1

我有一個簡單的滾動圖,它使用這種方法來繪製自己。我正在尋找一種將文本標籤添加到此圖表的方法,但無法找到如何執行此操作的方法。iPhone iOS如何使用drawLayer在CALayer上繪製文本:inContext:?

我想:

[@"test" drawInRect: CGRectMake(0, 0, 10, 10) withFont:[UIFont systemFontOfSize:8]]; 

,我得到錯誤信息說無效的情況下爲0x0。 如何修改以下代碼以將文本繪圖代碼指向正確的上下文?

-(void)drawLayer:(CALayer*)l inContext:(CGContextRef)context 
{ 
    // Fill in the background 
    CGContextSetFillColorWithColor(context, graphBackgroundColor()); 
    CGContextFillRect(context, layer.bounds); 

    // Draw the grid lines 
// DrawGridlines(context, 0.0, 32.0); 

    // Draw the graph 
    CGPoint lines[64]; 
    int i; 
    // X 
    for(i = 0; i < 32; ++i) 
    { 
     lines[i*2].x = i; 
     lines[i*2].y = -(xhistory[i] * 480.0)-10; 
     lines[i*2+1].x = i + 1; 
     lines[i*2+1].y = -(xhistory[i+1] * 480.0)-10; 
    } 

    CGContextSetStrokeColorWithColor(context, graphZColor()); 
    CGContextStrokeLineSegments(context, lines, 64); 
} 
+0

您可以添加一個CATextLayer作爲圖層的子圖層。 – 2013-05-09 21:55:19

回答

3

對於每個線程,UIKit都維護一堆圖形上下文。您可以通過調用UIGraphicsGetCurrentContext來獲取當前線程堆棧頂部的上下文。

當您使用drawInRect:withFont:,字符串繪製自己被UIGraphicsGetCurrentContext返回的上下文,所以你需要做UIGraphicsGetCurrentContext回用UIGraphicsPushContextdrawLayer:inContext:context說法。完成繪圖後,您必須致電UIGraphicsPopContext。因此:

-(void)drawLayer:(CALayer*)l inContext:(CGContextRef)context { 
    UIGraphicsPushContext(context); { 
     // Fill in the background 
     CGContextSetFillColorWithColor(context, graphBackgroundColor()); 
     CGContextFillRect(context, layer.bounds); 
     // etc. 
    } UIGraphicsPopContext(); 
} 
相關問題