Shadow UIview and clipsToBounds

15

我想给我的容器UIView添加阴影效果。我使用以下代码实现:

- (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;
}

这个效果很好。但是,当我在这个容器UIView上使用_containerView.clipsToBounds = YES;时,我看不到我的阴影。为什么?


你可以在这里阅读有关 clipsToBounds 的信息:https://dev59.com/zGIj5IYBdhLWcg3wRTH2 - megimix
4个回答

30

clipsToBounds属性还会剪切你的阴影,为了避免这种情况,你可以添加_containerView.layer.masksToBounds = NO来禁止子层被剪切(更多详情请参见此处)。


2
感谢masksToBounds - Islam

12
如果您必须使用clipsToBounds = true,因为您不希望子视图超出视图的边框,但同时需要在视图上添加阴影,我建议在视图后面添加一个额外的视图,并在额外的视图上设置阴影属性。
//run this in viewDidLoad() or your initialisation code
private func setupShadowContainer() {
    let containerShadow = UIView()
    parentView.addSubview(containerShadow)
    containerShadow.dropShadow()
    //using SnapKit here, you can use NSLayoutConstraint in a similar way to constraint the containerShadow behind your View
    containerShadow.snp.makeConstraints { (make) in
        make.edges.equalTo(yourView.snp.edges)
    }
}

//dropShadow method
extension UIView {
    func dropShadow() {
        self.translatesAutoresizingMaskIntoConstraints = false
        self.layer.shadowRadius = 3
        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
        self.layer.shadowOpacity = 0.5
        self.layer.masksToBounds = false
    }
}

如果阴影没有显示,您可能需要在containerShadow上设置一个随机背景颜色。 - Lexon Li
我建议在你的视图后面添加一个额外的视图,并在额外的视图上设置阴影属性。好的解决方案。谢谢。 - Ali Ihsan URAL

1
这是UIView扩展。
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
    }
}

在创建视图后,请按以下方式调用此函数:
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;
}

11
需要翻译的内容:Couldn't throw in even a short sentence explaining this?您能加入一句简短的解释吗? - nenchev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接