title: iOS create the inverse of a CAShapeLayer mask
body: <p>So I am a fresh iOS developer working on an iOS drawing application that plays back user sketches using x/y coordinates and timestamps.  To draw simple pen events i have a UIView that serves as the drawing view and I draw to the view using CAShapeLayers like so:</p>
  
  <pre><code>if (index == 0){
      CGPathMoveToPoint(path, NULL, point.x, point.y);
  } else {
      CGPathAddLineToPoint(path, NULL, point.x, point.y);
  }
  
  ……
  
  CAShapeLayer *permLayer = [CAShapeLayer layer];
          [permLayer setFrame:CGRectMake(0, 0, 1024, 640)];
          [permLayer setFillColor:[[UIColor clearColor] CGColor]];
          [permLayer setStrokeColor:currentColor.CGColor];
          [permLayer setLineWidth:[event[@"strokeWeight"] floatValue]];
          [permLayer setLineJoin:kCALineJoinRound];
          [permLayer setLineCap:kCALineCapRound];
  
  ……
  
  [[self layer] addSublayer:permLayer];
  
  ……
  </code></pre>
  
  <p>All is good and it looks fine:</p>
  
  <p><img src="https://i.stack.imgur.com/o1z80.png" alt="enter image description here"></p>
  
  <p>Now what I want to do is have an erase event that looks like:</p>
  
  <p><img src="https://i.stack.imgur.com/2mEUr.png" alt="enter image description here"></p>
  
  <p>I tried to accomplish this using another CAShapeLayer as a mask and drawing the CGPath of the erase event to that mask.  However what I ended up with was this:</p>
  
  <p><img src="https://i.stack.imgur.com/EcRdG.png" alt="enter image description here"></p>
  
  <p>….which is the exact opposite of what I want.  I guess I need to somehow get the inverse mask of the CAShapeLayer created by the CGPath of the erase event?  I’m not sure what the proper way to approach this would be without a lot of math that I’m not familiar with.</p>
  
  <p>The other caveat is that this animation is tied to CADisplayLink so these drawing animations are being refreshed very often and performance is important.  I’ve tried before with drawing to UIImages instead of CAShapeLayers and using kCGBlendModeClear to achieve the erase effect, but performance suffered terribly.  Thanks for any advice or insights!</p>