我有一个使用此方法绘制自身的简单滚动图。我正在寻找一种向该图形添加文本标签的方法,但是找不到如何执行此操作。

我试过了:

[@"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);
}

最佳答案

对于每个线程,UIKit都会维护一堆图形上下文。您可以通过调用UIGraphicsGetCurrentContext获得当前线程栈顶部的上下文。

当您使用drawInRect:withFont:时,字符串会将自身吸引到UIGraphicsGetCurrentContext返回的上下文,因此您需要使UIGraphicsGetCurrentContext使用context返回drawLayer:inContext:UIGraphicsPushContext参数。完成绘制后,必须调用UIGraphicsPopContext。从而:

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

10-07 19:55
查看更多