CGContext无效上下文0x0

时间:2014-03-06 12:38:13

标签: ios uikit core-graphics cgcontext cglayer

我正在绘制CGlayers,所以我在drawRect方法中创建Layer并将Layer绘制到图形上下文中,这样

- (void)drawRect:(CGRect)rect
{              
     CGContextRef context = UIGraphicsGetCurrentContext();
     if(self.currentDrawingLayer == nil)
     {
         CGLayerRef layer = CGLayerCreateWithContext(context, bounds.size, NULL);   
          self.currentDrawingLayer = layer;
     }                  

     CGContextDrawLayerInRect(context, self.bounds, self.currentDrawingLayer);       

}

我在touchesMoved函数中执行所有绘图操作

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
      CGContextRef layerContext =  CGLayerGetContext(self.currentDrawingLayer);

      CGContextSetLineCap(layerContext, kCGLineCapRound);
      CGContextSetLineJoin(layerContext, kCGLineJoinRound);
      CGContextSetAllowsAntialiasing(layerContext, YES);
      CGContextSetShouldAntialias(layerContext, YES);
      CGContextSetBlendMode(layerContext,kCGBlendModeClear);
      CGContextSetLineWidth(layerContext, self.eraseWidth);
      CGContextBeginPath(layerContext);
      CGContextAddPath(layerContext, mutablePath);
      CGContextStrokePath(layerContext);
      CGPathRelease(mutablePath);

      [self setNeedsDisplay];
}

但是当我开始绘图时,我得到移动触摸中使用的所有CGContext函数的错误消息,我在下面列出了几个。

<Error>: CGContextBeginPath: 
 This is a serious error. This application, or a library it uses, is using an invalid context  and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.
<Error>: CGContextAddPath: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context  and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.
  1. 我知道错误是因为,还没有创建Layer,因此,我得到了这个错误,但是应该只在drawRect方法中创建Layer,因为它是图形上下文存活的地方。
  2. 如果我首先调用[self setNeedsDisplay]然后再调用我的绘图函数,再次调用[self setNeedsDisplay],那么一切正常,没有错误,但我不认为,或者更确切地说不知道这是什么正确的事情。

1 个答案:

答案 0 :(得分:0)

-touchesMoved:withEvent:方法中,如果您还没有图层,请返回。毕竟,如果用户无法看到您的视图,则无法进行绘制。即添加

 if (!self.currentDrawingLayer)
   return;

在顶部。