【问题标题】:iPhone iOS how to draw text on a CALayer using drawLayer:inContext:?iPhone iOS 如何使用 drawLayer:inContext: 在 CALayer 上绘制文本?
【发布时间】:2013-05-09 21:38:48
【问题描述】:

我有一个简单的滚动图,它使用这种方法来绘制自己。我正在寻找一种将文本标签添加到此图表的方法,但找不到如何执行此操作。

我试过了:

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

【问题讨论】:

  • 你可以添加一个 CATextLayer 作为你的图层的子图层。

标签: iphone ios objective-c core-graphics calayer


【解决方案1】:

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

当您使用drawInRect:withFont: 时,字符串会将自身吸引到UIGraphicsGetCurrentContext 返回的上下文,因此您需要使用UIGraphicsPushContext 使UIGraphicsGetCurrentContext 返回drawLayer: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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 2012-07-21
    相关资源
    最近更新 更多