Shadow on the UIView layer

I created a path to mask my view:

let path = // create magic path (uiview bounds + 2 arcs) let mask = CAShapeLayer() mask.path = path.cgPath view.layer.masksToBounds = false view.layer.mask = mask 

So far, everything is fine.

Now I would like to add a shadow that follows the path, is this possible?

I try in several ways, the last one is:

 mask.shadowPath = path.cgPath mask.shadowColor = UIColor.red.cgColor mask.shadowOffset = CGSize(width: 10, height: 2.0) mask.shadowOpacity = 0.5 

But this creates a partial shadow and color of the original look.

enter image description here

With debug view hierarchy:

enter image description here

Any tips?

The end result should be similar to this, but with a shadow that β€œfollows” the arcs in the path.

enter image description here

+6
source share
2 answers

When you add a mask to a layer, it grips anything outside of that mask, including the shadow. To achieve this, you need to add a β€œshadow” view below your masked view, which has the same path as the mask.

Or add a shadow layer to the hidden superview .

 let view = UIView(frame: CGRect(x: 50, y: 70, width: 100, height: 60)) view.backgroundColor = .cyan let mask = CAShapeLayer() mask.path = UIBezierPath(roundedRect: view.bounds, cornerRadius: 10).cgPath view.layer.mask = mask let shadowLayer = CAShapeLayer() shadowLayer.frame = view.frame shadowLayer.path = UIBezierPath(roundedRect: view.bounds, cornerRadius: 10).cgPath shadowLayer.shadowOpacity = 0.5 shadowLayer.shadowRadius = 5 shadowLayer.masksToBounds = false shadowLayer.shadowOffset = .zero let container = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) container.backgroundColor = .white container.layer.addSublayer(shadowLayer) container.addSubview(view) 

enter image description here

If you intend to use it elsewhere, you can create a ShadowMaskedView that contains the shadow layer, and a hidden view - possibly with the path property.

+7
source

You can try this extension:

 extension UIView { func dropShadow() { self.layer.masksToBounds = false self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOpacity = 0.5 self.layer.shadowOffset = CGSize(width: -1, height: 1) self.layer.shadowRadius = 1 self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath self.layer.shouldRasterize = true } } 
-one
source

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


All Articles