Is there a way to prevent overlapping CALayer shadows from adjacent layers?

I have a collection of CALayers . Each layer is a sublayer of the same CALayer parent, and each of them has a shadow applied to it. Layers are located dynamically, and there are many of them, so I can not predict how they will be organized ahead of time.

If the layers are adjacent to each other (close enough to almost touch), the shadow of one of the CALayers displayed on top of the other CALayer . This is probably the desired effect in most cases, but I want my layers to exist in the same z-plane. (An example of this is the way CSS3 shadows are used for block elements in web design.)

Is it possible? How can I achieve this?

(I had this idea: adding a β€œshadow” sublevel to each CALayer with my own shadow image and setting the z-position to a lower value. But doesn’t the layer tree make this impossible? -Position in a single-level coordinate system does not depend on z-positions in another layer coordinate system, right?)

+6
source share
1 answer

If all the shaded layers have the same shadow settings, put them in the container layer and set the shadow at the container level. Example:

 - (void)viewDidLoad { [super viewDidLoad]; CALayer *containerLayer = [CALayer layer]; containerLayer.frame = self.view.bounds; containerLayer.shadowRadius = 10; containerLayer.shadowOpacity = 1; [self.view.layer addSublayer:containerLayer]; CAShapeLayer *layer1 = [CAShapeLayer layer]; layer1.bounds = CGRectMake(0, 0, 200, 200); layer1.position = CGPointMake(130, 130); layer1.path = [UIBezierPath bezierPathWithOvalInRect:layer1.bounds].CGPath; layer1.fillColor = [UIColor redColor].CGColor; [containerLayer addSublayer:layer1]; CAShapeLayer *layer2 = [CAShapeLayer layer]; layer2.bounds = CGRectMake(0, 0, 200, 200); layer2.position = CGPointMake(170, 200); layer2.path = [UIBezierPath bezierPathWithOvalInRect:layer2.bounds].CGPath; layer2.fillColor = [UIColor blueColor].CGColor; [containerLayer addSublayer:layer2]; } 

Conclusion:

overlapping circles with unified shadow

+16
source

Source: https://habr.com/ru/post/903645/


All Articles