您的位置:首页 > 其它

<Error>: CGContextSetFont: invalid context 0x0

2013-01-05 13:33 441 查看
今天使用 subclass CAlayer,然后后在

-(void)drawInContext:(CGContextRef)ctx 方法中绘制文字



  CGRect bounds=CGContextGetClipBoundingBox(ctx);

    NSString * menueTxt1=NSLocalizedString(@"menue1","No Resource");

    UIFont * font=[UIFont systemFontOfSize:18.0f];

    CGRect menueTxtRect;

    menueTxtRect.origin.x=bounds.origin.x;

    menueTxtRect.origin.y=bounds.origin.y;

    //sizeWithFont:constrainedToSize:

    menueTxtRect.size=[menueTxt1 sizeWithFont:font constrainedToSize:CGSizeMake(30, 50)];

   // CGColorRef shadowClr=[[UIColor darkGrayColor]CG Color];

  //  CGContextSetShadowWithColor(ctx, CGSizeMake(0.0f, 2.0f), 1.0, shadowClr);

    [menueTxt1 drawInRect:menueTxtRect withFont:font];



但却抛出了

<Error>: CGContextSetFont: invalid context 0x0 这样的异常,意思就是这个CGContext is NULL, 为什么会这样呢,

在这方法中使用  CGContextRef ctx2=UIGraphicsGetCurrentContext(); 发现原来是空的,因些猜想在subclass UIVIEW 中的- (void)drawRect:(CGRect)rect 方法,

我们都是这样的获取,但这个是由系统在需要绘制前已经准备好了,而NNString 拿的就是context ,但在subclass CALayer 时这个估计是另外的机制,目前我也只能这么猜想

所以get到的是NULL, 由于此时方法的参数其实已经有这个context 了,我们可以使用这个CGContextRef,,

当时的猜想是不同的thread 造成的,但使用

if ([[NSThread currentThread]isMainThread]) {

        NSLog(@"this is main drawInContext");

    }

    NSLog(@"current thread in drawInContext %@",[NSThread currentThread]);

发现在controller loadView 方法,与这个drawInContext:大家都是main thread

突然想到的:

 UIGraphicsPushContext(ctx);

 UIGraphicsPopContext();

看IOS 文档的解析,current context 可以看成是一个当前线程维护的一个变量,暂时这么看吧。

UIGraphicsPushContext

Makes the specified graphics context the current context.

void UIGraphicsPushContext (

   CGContextRef context

);

Parameters

context

The graphics context to make the current context.

Discussion

You can use this function to save the previous graphics state and make the specified context the current context.

You must balance calls to this function with matching calls to the UIGraphicsPopContext function.

In iOS 4 and later, you may call this function from any thread of your app.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐