如何在Objective-C中设置CAShapeLayer透明?

时间:2022-08-26 21:44:17

I'm trying to setup a inset shadow on a UIButton, Thanks to other SO posts, I've managed to do this :

我正在尝试在UIButton上设置插入阴影,感谢其他SO帖子,我设法做到了这一点:

        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).

我确实得到了一个漂亮的白色内阴影,但是shadowLayer添加了一个黑色的不透明矩形(阴影路径)。

Tried [shadowLayer setFillColor:UIColor.clearColor.CGColor]; but it removes the shadow as well. Also [shadowLayer setBackgroundColor:UIColor.redColor.CGColor]; does nothing.

尝试[shadowLayer setFillColor:UIColor.clearColor.CGColor];但它也消除了阴影。另外[shadowLayer setBackgroundColor:UIColor.redColor.CGColor];什么也没做。

如何在Objective-C中设置CAShapeLayer透明?

How can I get rid of it?!

我怎么能摆脱它?!

1 个解决方案

#1


1  

Adding a [self.layer setMasksToBounds:YES]; solved the issue!

添加[self.layer setMasksToBounds:YES];解决了这个问题!

#1


1  

Adding a [self.layer setMasksToBounds:YES]; solved the issue!

添加[self.layer setMasksToBounds:YES];解决了这个问题!