How can set a CAShapeLayer transparent in Objective-C?
-
26-06-2021 - |
Question
I'm trying to setup a inset shadow on a UIButton, Thanks to other SO posts, I've managed to do this :
UIBezierPath *buttonPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:self.layer.cornerRadius];
CAShapeLayer* shadowLayer = [CAShapeLayer layer];
//shadowLayer.cornerRadius = 8.0f;
[shadowLayer setOpacity:1];
//[shadowLayer setBackgroundColor:UIColor.redColor.CGColor]; //not working
// Standard shadow stuff
[shadowLayer setShadowOpacity:1.0f];
[shadowLayer setShadowColor:[[UIColor colorWithWhite:1 alpha:1] CGColor]];
[shadowLayer setShadowOffset:CGSizeMake(2.0f, 2.0f)];
[shadowLayer setShadowRadius:5];
// Causes the inner region in this example to NOT be filled.
[shadowLayer setFillRule:kCAFillRuleEvenOdd];
// Create the larger rectangle path.
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectInset(self.bounds, -42.0f, -42.0f));
// Add the inner path so it's subtracted from the outer path.
CGPathAddPath(path, NULL, buttonPath.CGPath);
CGPathCloseSubpath(path);
[shadowLayer setPath:path];
CGPathRelease(path);
[self.layer addSublayer:shadowLayer];
I do get a nice white inner shadow, however the shadowLayer adds a black opaque rect (the shadow path).
Tried [shadowLayer setFillColor:UIColor.clearColor.CGColor];
but it removes the shadow as well. Also [shadowLayer setBackgroundColor:UIColor.redColor.CGColor];
does nothing.
How can I get rid of it?!
Solution
Adding a [self.layer setMasksToBounds:YES];
solved the issue!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow