How to mask and add shadow to a UIView

ilan picture ilan · Jun 1, 2016 · Viewed 8.2k times · Source

I'm making a custom view that i want to mask and to add shadow to it.

the masking:

    let p = UIBezierPath()
    p.moveToPoint(CGPointMake(20, 20))
    p.addLineToPoint(CGPointMake(100, 20))
    p.addLineToPoint(CGPointMake(100, 50))
    p.addLineToPoint(CGPointMake(110, 55))
    p.addLineToPoint(CGPointMake(100, 60))
    p.addLineToPoint(CGPointMake(100, 100))
    p.addLineToPoint(CGPointMake(20, 100))
    p.closePath()

    let s = CAShapeLayer()
    s.frame = layer.bounds
    s.path = p.CGPath
    s.fillColor = UIColor.greenColor().CGColor
    layer.mask = s

the masking works, now i want to add a shadow. but its not working.

i tried to add shadow to the main layer and nothing happens.

    layer.shadowColor = UIColor.yellowColor().CGColor
    layer.shadowRadius = 10
    layer.shadowOpacity = 0.9
    layer.shadowOffset = CGSizeZero

i tried to add it to the mask layer and i got the main view masked with a shadow.

    s.shadowColor = UIColor.yellowColor().CGColor
    s.shadowRadius = 10
    s.shadowOpacity = 0.9
    s.shadowOffset = CGSizeZero

Any suggestions how to add this yellow shadow to the masked view?

Thanks

Answer

ilan picture ilan · Jun 1, 2016

Thanks @WilsonXJ I changed mask to addSubLayer.

This is the answer that worked for me:

    let p = UIBezierPath()
    p.moveToPoint(CGPointMake(20, 20))
    p.addLineToPoint(CGPointMake(100, 20))
    p.addLineToPoint(CGPointMake(100, 50))
    p.addLineToPoint(CGPointMake(110, 55))
    p.addLineToPoint(CGPointMake(100, 60))
    p.addLineToPoint(CGPointMake(100, 100))
    p.addLineToPoint(CGPointMake(20, 100))
    p.closePath()

    let s = CAShapeLayer()
    s.fillColor = UIColor.whiteColor().CGColor
    s.frame = layer.bounds
    s.path = p.CGPath

    layer.backgroundColor = UIColor.clearColor().CGColor
    layer.addSublayer(s)

    layer.masksToBounds = true
    layer.shadowColor = UIColor.yellowColor().CGColor
    layer.shadowOffset = CGSizeZero
    layer.shadowOpacity = 0.9
    layer.shadowPath = p.CGPath
    layer.shadowRadius = 10