0

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

- (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. 我知道错误是因为尚未创建图层,因此,我收到此错误,但是应该在 drawRect 方法中创建图层,只是因为它的图形上下文是活动的。
  2. 如果我[self setNeedsDisplay]先调用我的绘图函数,最后再调用[self setNeedsDisplay],那么一切正常,没有错误,但我不认为,或者不知道这是否是正确的做法。
4

1 回答 1

0

在您的-touchesMoved:withEvent:方法中,如果您还没有图层,只需返回。毕竟,如果用户看不到您的视图,他们就无法绘图。即添加

 if (!self.currentDrawingLayer)
   return;

在顶部。

于 2014-03-06T12:46:36.037 回答