Search code examples
iosswiftuiviewcustom-controlscalayer

Preserve Shadow of a Masked UIView


I am trying to create a Half circle UIView with shadow.

What I did was:

  1. Create an UIView.
  2. Set it's backgroundColor to white
  3. Set the CornerRadius so it became a circle
  4. Add Shadow to it using view.layer.shadow properties

    circleView.backgroundColor = UIColor.whiteColor();
    
    circleView.layer.cornerRadius = baseRoundView.bounds.height/2 ;
    
    circleView.layer.shadowColor = UIColor.blackColor().CGColor;
    circleView.layer.shadowOffset = CGSize(width: 0, height: -3);
    circleView.layer.shadowOpacity = 0.1;
    circleView.layer.shadowRadius = 1;
    

    But those steps only got me a FULL CIRCLE UIVIEW with shadow.

Full Circle

So I tried to mask the lower half

    var maskRect: CGRect = CGRect(x: 0, y: 0), width: self.circleView.bounds.width, height: self.circleView.bounds.height/2);
    var path = CGPathCreateWithRect(maskRect, nil);

    maskLayer.path = path;

    circleView.layer.mask = maskLayer;

Those steps works well, except that I lost the top shadow issing Shadow

What I expect to have

Expectation

Any ideas?


Solution

  • As Larme pointed out in the comment , all I had to do is to adjust the Y position of maskLayer to cover the shadow.

    var maskRect: CGRect = CGRect(x: 0, y: -3), width: self.circleView.bounds.width, height: self.circleView.bounds.height/2 + 3  );