Why masksToBounds = YES prevents CALayer shadow?

后端 未结 6 1248
借酒劲吻你
借酒劲吻你 2020-11-28 01:44

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 prope

6条回答
  •  执笔经年
    2020-11-28 02:33

    It's iOS 6 now, things might have changed. TheSquad's answer don't work for me until I managed to add one more line view2.layer.masksToBounds = NO;, otherwise shadow doesn't show. Although documentation says masksToBounds is NO by default, my code shows the opposite.

    Here is how I make a rounded corner button with shadow, which is among the most commonly used code snippet in my app.

    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 10.0f;
    
    view.layer.masksToBounds = NO;      // critical to add this line
    view.layer.cornerRadius = 10.0f;
    view.layer.shadowOpacity = 1.0f;
    // set shadow path to prevent horrible performance
    view.layer.shadowPath = 
        [UIBezierPath bezierPathWithRoundedRect:_button.bounds cornerRadius:10.0f].CGPath;      
    
    [view addSubview:button];
    

    EDIT

    If views need to be animated or scrolled, masksToBounds = YES tax performance significantly, which means animation will probably get stuttered. To get rounded corner and shadow AND smooth animation or scrolling, use following code instead:

    button.backgroundColor = [UIColor clearColor];
    button.layer.backgroundColor = [UIColor redColor].CGColor;
    button.layer.masksToBounds = NO;
    button.layer.cornerRadius = 10.0f;
    
    view.layer.shadowOpacity = 0.5f;
    view.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:_button.bounds cornerRadius:10.0f].CGPath;
    view.layer.shadowOffset = CGSizeMake(0.0f, 4.0f);
    view.layer.shadowRadius = 2.0f;
    view.layer.masksToBounds = NO;
    view.layer.cornerRadius = 10.0f;  
    
    [view addSubview:button];
    

提交回复
热议问题