3

I want to create a mask layer which is a circle that makes the circle content transparent and keep everything around. Unfortunately, the following code does the opposite, it draws a circle and make everything around transparent.

CAShapeLayer * shape = [CAShapeLayer layer];
shape.frame          = CGRectMake((CGSSize().width/2.f)-40.f, -40.f, 80.f, 80.f);

CGPathRef pathRef    =
CGPathCreateWithEllipseInRect(CGRectMakeBoundsWithSize(shape.frame.size), NULL);

shape.path            = pathRef;
shape.fillColor       = [UIColor blueColor].CGColor;

self.layer.mask = shape;
Nicolas Manzini
  • 8,379
  • 6
  • 63
  • 81

1 Answers1

12

Yeah, kCAFillRuleEvenOdd didn't do it's magic without adding a rect first, here is a working snippet though:

CAShapeLayer *shape = [CAShapeLayer layer];

shape.frame = self.bounds;

CGMutablePathRef pathRef = CGPathCreateMutable();
CGPathAddRect(pathRef, NULL, self.bounds);
CGPathAddEllipseInRect(pathRef, NULL, self.bounds);

shape.fillRule = kCAFillRuleEvenOdd;
shape.path = pathRef;

self.layer.mask = shape;
Rick van der Linde
  • 2,581
  • 1
  • 20
  • 22
  • 1
    Yes thank you. The key to mask acting as a hole in the layer is 1. Mutable Path that adds a rect first, then adds the ellipse, so that 2. kCAFillRuleEvenOdd functions on the ellipse as the "punch out hole". – ObjectiveTC Sep 23 '15 at 03:00