UIView图层上的阴影 [英] Shadow on UIView layer

查看:73
本文介绍了UIView图层上的阴影的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了掩盖我的观点,我做了一条路:

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:

有什么建议吗?

最终结果应该与此相似,但是阴影会跟随"路径上的弧线.

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.

或在蒙版视图的 superview 中添加阴影层.

Or add a shadow layer to the masked view's 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)

如果要在其他地方使用它,则可以创建一个 ShadowMaskedView ,其中包含阴影层和蒙版视图-可能具有path属性.

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.

这篇关于UIView图层上的阴影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆