Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why masksToBounds = YES prevents CALayer shadow?

With the following snippet, I'm adding a drop shadow effect to one my UIView. Which works pretty well. But as soon as I set the view's masksToBounds property to YES. The drop shadow effect isn't rendered any more.

self.myView.layer.shadowColor = [[UIColor blackColor] CGColor]; self.myView.layer.shadowOpacity = 1.0; self.myView.layer.shadowRadius = 10.0; self.myView.layer.shadowOffset = CGSizeMake(0.0f, 0.0f); self.myView.layer.cornerRadius = 5.0; self.myView.layer.masksToBounds = YES; // <-- This is causing the Drop shadow to not be rendered UIBezierPath *path = [UIBezierPath bezierPathWithCurvedShadowForRect:self.myView.bounds]; self.myView.layer.shadowPath = path.CGPath; self.myView.layer.shouldRasterize = YES; 

Do you have any ideas on this?

like image 587
jchatard Avatar asked Sep 11 '10 12:09

jchatard


1 Answers

Because shadow is an effect done outside the View, and that masksToBounds set to YES will tell the UIView not to draw anything that is outside itself.

If you want a roundedCorner view with shadow I suggest you do it with 2 views:

UIView *view1 = [[UIView alloc] init]; UIView *view2 = [[UIView alloc] init];  view1.layer.cornerRadius = 5.0; view1.layer.masksToBounds = YES; view2.layer.cornerRadius = 5.0; view2.layer.shadowColor = [[UIColor blackColor] CGColor]; view2.layer.shadowOpacity = 1.0; view2.layer.shadowRadius = 10.0; view2.layer.shadowOffset = CGSizeMake(0.0f, 0.0f); [view2 addSubview:view1]; [view1 release]; 
like image 145
TheSquad Avatar answered Sep 25 '22 15:09

TheSquad