<Error>: CGContextSetFont: invalid context 0x0

今天使用 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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值