簡體   English   中英

陰影 UIview 和 clipsToBounds

[英]Shadow UIview and clipsToBounds

我想為我的容器 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;
}

這很好用。 但是,當我使用_containerView.clipsToBounds = YES; 在這個容器 UIView 上,我看不到我的影子。 為什么?

clipsToBounds還會剪輯您的陰影。 為了防止這種情況,您可以添加_containerView.layer.masksToBounds = NO以禁用子圖層的剪輯(請在此處查看更多信息)。

如果您必須使用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
    }
}

這是 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)
- (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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM