ios – 仅将CALayer阴影屏蔽到rect之外

前端之家收集整理的这篇文章主要介绍了ios – 仅将CALayer阴影屏蔽到rect之外前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我如何用阴影掩盖CALayer,以便阴影只在路径之外?我不希望透明视图背后的阴影.
shadowLayer.shadowOffset = CGSizeMake(x,y);
shadowLayer.shadowRadius = radius;
shadowLayer.shadowOpacity = opacity;
shadowLayer.shadowColor = color.CGColor;
shadowLayer.shadowPath = [UIBezierPath bezierPathWithRect:view.bounds].CGPath;

谢谢.

解决方法

我会回答我自己的问题.为视图添加新的阴影层.如果设置正确,这应适用于任何shadowPath.
float radius = 8;
float opacity = 0.5f;
float x = 4;
float y = 6;
UIColor *color = [UIColor blackColor];

// Shadow layer
CALayer *shadowLayer = [CALayer layer];
shadowLayer.shadowOffset = CGSizeMake(x,y);
shadowLayer.shadowRadius = radius;
shadowLayer.shadowOpacity = opacity;
shadowLayer.shadowColor = color.CGColor;
shadowLayer.shadowPath = [UIBezierPath bezierPathWithRect:view.frame].CGPath; // Or any other path

// Shadow mask frame
CGRect frame = CGRectInset(view.layer.frame,-2*radius,-2*radius);
frame = CGRectOffset(frame,x,y);

// Translate shadowLayer shadow path to mask layer's coordinate system
CGAffineTransform trans = CGAffineTransformMakeTranslation(-view.frame.origin.x-x+2*radius,-view.frame.origin.y-y+2*radius);

// Mask path
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path,nil,(CGRect){.origin={0,0},.size=frame.size});
CGPathAddPath(path,&trans,shadowLayer.shadowPath);
CGPathCloseSubpath(path);

// Mask layer
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = frame;
maskLayer.fillRule = kCAFillRuleEvenOdd;
maskLayer.path = path;

shadowLayer.mask = maskLayer;

[view.layer.superlayer insertSublayer:shadowLayer below:view.layer];

猜你在找的iOS相关文章