简体   繁体   English

UIView图层上的阴影

[英]Shadow on UIView layer

I've make a path in order to mask my view: 我已经制作了一条路径来掩盖我的观点:

let path = // create magic path (uiview bounds + 2 arcs)
let mask = CAShapeLayer()
mask.path = path.cgPath
view.layer.masksToBounds = false
view.layer.mask = mask

Up to here all ok. 到目前为止一切都好。

Now I would like to add a shadow that follows path, is it possibile? 现在我想添加一个跟随路径的阴影,它可能吗?

I try in several way, the last one is: 我尝试了几种方式,最后一种是:

mask.shadowPath = path.cgPath
mask.shadowColor = UIColor.red.cgColor
mask.shadowOffset = CGSize(width: 10, height: 2.0)       
mask.shadowOpacity = 0.5

But this produce a partial shadow and with color of the original view.. 但这会产生局部阴影和原始视图的颜色。

在此输入图像描述

With debug view hierarchy: 使用调试视图层次结构

在此输入图像描述

Any advice? 有什么建议?

Final result should be similar to this, but with shadow that "follows" arcs on path. 最终结果应与此类似,但阴影“跟随”路径上的弧。

在此输入图像描述

When you add a mask to a layer, it clips anything outside that mask - including the shadow. 当您向图层添加蒙版时,它会剪切该蒙版之外的任何内容 - 包括阴影。 To achieve this you'll need to add a "shadow" view below your masked view, that has the same path as the mask. 要实现此目的,您需要在蒙版视图下方添加一个“阴影”视图,该视图与蒙版具有相同的路径。

Or add a shadow layer to the masked view's superview . 或者将阴影图层添加到蒙版视图的超superview

let view = UIView(frame: CGRect(x: 50, y: 70, width: 100, height: 60))
view.backgroundColor = .cyan

let mask = CAShapeLayer()
mask.path = UIBezierPath(roundedRect: view.bounds, cornerRadius: 10).cgPath
view.layer.mask = mask

let shadowLayer = CAShapeLayer()
shadowLayer.frame = view.frame
shadowLayer.path = UIBezierPath(roundedRect: view.bounds, cornerRadius: 10).cgPath
shadowLayer.shadowOpacity = 0.5
shadowLayer.shadowRadius = 5
shadowLayer.masksToBounds = false
shadowLayer.shadowOffset = .zero    

let container = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
container.backgroundColor = .white
container.layer.addSublayer(shadowLayer)
container.addSubview(view)

在此输入图像描述

If you're going to be using this elsewhere, you could create a ShadowMaskedView that contains the shadow layer, and the masked view - maybe with a path property. 如果你打算在其他地方使用它,你可以创建一个包含阴影层的ShadowMaskedView和蒙版视图 - 可能带有路径属性。

You can try this extension: 你可以尝试这个扩展:

extension UIView {

    func dropShadow() {

        self.layer.masksToBounds = false
        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.shadowOpacity = 0.5
        self.layer.shadowOffset = CGSize(width: -1, height: 1)
        self.layer.shadowRadius = 1

        self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
        self.layer.shouldRasterize = true
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM