2013-05-09 73 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(); 
} 
相关问题