问题
I would like to set the shadow to my container UIView. I use this code to make it:
- (id)initWithCoder:(NSCoder*)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
//-> drop shadow
[self.layer setShadowColor:[UIColor blackColor].CGColor];
[self.layer setShadowOpacity:0.6];
[self.layer setShadowRadius:2.0];
[self.layer setShadowOffset:CGSizeMake(2.0, 2.0)];
}
return self;
}
This works well. But, when I use _containerView.clipsToBounds = YES;
on this container UIView, I can't see my shadow. Why?
回答1:
the clipsToBounds
also clips your shadow. In order to prevent this you can add _containerView.layer.masksToBounds = NO
which disables clipping of sublayers (see more here).
回答2:
Here is the UIView extension.
extension UIView {
func addShadowAndRoundCorner(cornerRadius : CGFloat) {
self.layer.shadowOffset = .zero
self.layer.shadowOpacity = 0.5
self.layer.shadowRadius = 3
self.layer.shadowColor = UIColor.black.cgColor
self.layer.masksToBounds = false
self.layer.cornerRadius = cornerRadius
}
}
Call this function after creation of view as follows:
let roundView = UIView()
roundView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 100)
roundView.addShadowAndRoundCorner(cornerRadius: 100/2)
回答3:
- (void)layoutSubviews
{
[super layoutSubviews];
CAGradientLayer *l = [CAGradientLayer layer];
l.frame = self.bounds;
l.colors = [NSArray arrayWithObjects:(id)[UIColor clearColor].CGColor, (id)[UIColor whiteColor].CGColor, (id)[UIColor whiteColor].CGColor,(id)[UIColor whiteColor].CGColor,(id)[UIColor whiteColor].CGColor,(id)[UIColor whiteColor].CGColor, (id)[UIColor clearColor].CGColor,(id)[UIColor clearColor].CGColor, nil];
l.startPoint = CGPointMake(0.0f, 1.0f);
l.endPoint = CGPointMake(1.0f, 1.0f);
self.layer.mask = l;
}
来源:https://stackoverflow.com/questions/23760918/shadow-uiview-and-clipstobounds