如何向被路径遮罩的视图添加阴影 [英] How to add a shadow to a view that's masked with a path
问题描述
如何为被路径遮罩的视图添加阴影?
How do I add a shadow to a view that's masked with a path?
layer
有一个掩码属性,你可以像这样设置 yourCustomView.layer.mask = somePath
.但是我如何添加一个也被遮罩到 layer.mask
的阴影?
layer
has a mask property that you can set like this yourCustomView.layer.mask = somePath
. But how do I add a shadow that's also masked to the layer.mask
?
推荐答案
我看到这个问题问了很多,答案到处都是,所以我想我会集中一点.
I see this asked quite a bit and answers are all over the place, so I thought I would centralize a tad.
基本上,当您想为被路径遮罩的视图添加阴影时,事情就会变得有趣起来.
Basically when you want to add a shadow to a view that's masked with a path, things get interesting.
这是我构建的一个扩展程序,可以处理这一切并且非常易于使用.corners
参数是为基本的圆角设置而设置的,但您可以将其替换为您想要的任何 UIBezierPath.
This is an extension I built that handles it all and is really easy to use. The corners
argument is setup for a basic rounded corners setup, but you can replace that with whatever UIBezierPath you want.
import UIKit
public extension UIView {
/// You will probably need to call this from viewDidLayoutSubviews()
func roundCorners(corners: UIRectCorner = .bottomRight, radius: CGFloat = 40) {
layoutIfNeeded()
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
/// You will probably need to call this from viewDidLayoutSubviews()
func roundCornersWithShadow(corners: UIRectCorner = .bottomRight, cornerRadius radius: Double = 40, shadowOpacity: Float = 0.5, shadowRadius: Double = 4, shadowOffset: CGSize = CGSize(width: 0, height: 2), shadowColor: UIColor = .black, maskName: String = "mask", shadowName: String = "shadow") {
layoutIfNeeded()
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)).cgPath
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = path
layer.mask = maskLayer
layer.name = maskName
if let subLayers = superview?.layer.sublayers {
for layer in subLayers where layer.name == shadowName { layer.removeFromSuperlayer() }
}
let shadowLayer = CAShapeLayer()
shadowLayer.name = shadowName
shadowLayer.path = path
shadowLayer.frame = frame
shadowLayer.shadowOpacity = shadowOpacity
shadowLayer.shadowRadius = CGFloat(shadowRadius)
shadowLayer.shadowColor = shadowColor.cgColor
shadowLayer.shadowOffset = shadowOffset
superview?.layer.insertSublayer(shadowLayer, below: layer)
}
}
然后像这样使用它:
override func viewDidLayoutSubviews() {
...
yourView.roundCornersWithShadow(corners: [.bottomRight, .bottomLeft, .topRight, .topLeft]) // Use whatever corners you want.
}
这篇关于如何向被路径遮罩的视图添加阴影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!