Artyom Vlasenko
Artyom Vlasenko

Reputation: 385

How to add shadow to view with mask

enter image description hereI need to add shadow for view with shape aka trapezoid.

here is my code, and it doesn't work.

    [![enter image description here][1]][1]let trapezoidPath = UIBezierPath()
    trapezoidPath.move(to: CGPoint(x: 0, y: 0))
    trapezoidPath.addLine(to: CGPoint(x: Constants.padding, y: bounds.maxY - 10))
    trapezoidPath.addLine(to: CGPoint(x: titleLabel.bounds.width + Constants.padding, y: bounds.maxY - 10))
    trapezoidPath.addLine(to: CGPoint(x: titleLabel.bounds.width + 2 * Constants.padding, y: 0))

    let trapezoidLayer = CAShapeLayer()
    trapezoidLayer.path = trapezoidPath.cgPath
    
    whiteView.layer.shadowPath = UIBezierPath(roundedRect: trapezoidPath.bounds, cornerRadius: whiteView.layer.cornerRadius).cgPath
    whiteView.layer.shadowRadius = 15
    whiteView.layer.shadowOffset = .zero
    whiteView.layer.shadowOpacity = 0.4
    whiteView.layer.masksToBounds = false
    whiteView.layer.shadowColor = UIColor.red.cgColor

    whiteView.layer.mask = trapezoidLayer

Upvotes: 0

Views: 135

Answers (1)

anon
anon

Reputation:

Nothing outside your mask, including the shadow, will be drawn.

To fix this you need to create two views. The outer view should be transparent and have the shadow properties set. The inner view gets added as a subview to the outer view and has the layer mask configured.

Basically the inner view draws your shape and content and the outer view around it is only responsible for drawing the shadow.

Upvotes: 1

Related Questions