感谢Ashok R的快速代码,对其他答案有所改进。
由于我们在视图的背景中创建了一个三角形视图,所有边都带有阴影,因此不需要边上的白色三角形阴影。
如果视图的宽度相对大于高度,它会中断。
一种解决方法是将不需要阴影的线的路径稍微移向视图的那一侧,而不是完全创建三角形视图路径。
我为此创建了一个扩展 -
extension UIView {
func addshadow(top: Bool,
left: Bool,
bottom: Bool,
right: Bool,
shadowRadius: CGFloat = 2.0) {
self.layer.masksToBounds = false
self.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
self.layer.shadowRadius = shadowRadius
self.layer.shadowOpacity = 1.0
let path = UIBezierPath()
var x: CGFloat = 0
var y: CGFloat = 0
var viewWidth = self.frame.width
var viewHeight = self.frame.height
// here x, y, viewWidth, and viewHeight can be changed in
// order to play around with the shadow paths.
if (!top) {
y+=(shadowRadius+1)
}
if (!bottom) {
viewHeight-=(shadowRadius+1)
}
if (!left) {
x+=(shadowRadius+1)
}
if (!right) {
viewWidth-=(shadowRadius+1)
}
// selecting top most point
path.move(to: CGPoint(x: x, y: y))
// Move to the Bottom Left Corner, this will cover left edges
/*
|☐
*/
path.addLine(to: CGPoint(x: x, y: viewHeight))
// Move to the Bottom Right Corner, this will cover bottom edge
/*
☐
-
*/
path.addLine(to: CGPoint(x: viewWidth, y: viewHeight))
// Move to the Top Right Corner, this will cover right edge
/*
☐|
*/
path.addLine(to: CGPoint(x: viewWidth, y: y))
// Move back to the initial point, this will cover the top edge
/*
_
☐
*/
path.close()
self.layer.shadowPath = path.cgPath
}
并为您希望阴影出现的任何一侧设置布尔值 true
myView.addshadow(top: false, left: true, bottom: true, right: true, shadowRadius: 2.0)
// 阴影半径在上面是可选的,默认设置为 2.0
或者
myView.addshadow(top: true, left: true, bottom: true, right: true, shadowRadius: 2.0)
或者
myView.addshadow(top: false, left: false, bottom: true, right: true, shadowRadius: 2.0)