我构建了一个 View ,其中仅两个具有角半径的上角和两个正常 90 度角的底部角:
extension UIView {
func roundCorners(corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
}
我只需执行以下操作即可将其添加到我的 View 中:
override func layoutSubviews() {
super.layoutSubviews()
roundCorners(corners: [.topLeft, .topRight], radius: 15)
}
现在我想为其添加阴影,我尝试执行以下操作:
private var shadowLayer: CAShapeLayer!
override func layoutSubviews() {
super.layoutSubviews()
let corners: UIRectCorner = [.topLeft, .topRight]
let radius: CGFloat = 15
roundCorners(corners: corners, radius: radius)
if shadowLayer == nil {
shadowLayer = CAShapeLayer()
shadowLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)).cgPath
shadowLayer.fillColor = UIColor.white.cgColor
shadowLayer.shadowColor = UIColor.darkGray.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowOffset = CGSize(width: 2.0, height: 2.0)
shadowLayer.shadowOpacity = 0.3
shadowLayer.shadowRadius = 2
layer.insertSublayer(shadowLayer, at: 0)
}
}
但这似乎不起作用(阴影根本没有出现) 我怎样才能解决这个问题?
谢谢
最佳答案
我找到的解决方案:
private var shadowLayer: CAShapeLayer!
override func layoutSubviews() {
super.layoutSubviews()
self.backgroundColor = .clear
self.layer.masksToBounds = false
let radius: CGFloat = 30
if shadowLayer == nil {
shadowLayer = CAShapeLayer()
shadowLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft , .topRight], cornerRadii: CGSize(width: radius, height: radius)).cgPath
// shadowLayer.path = UIBezierPath(roundedRect: CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.width, height: bounds.height), byRoundingCorners: [.topLeft , .topRight], cornerRadii: CGSize(width: radius, height: radius)).cgPath // To change the shadow shape
shadowLayer.fillColor = UIColor.white.cgColor
shadowLayer.shadowColor = UIColor.lightGray.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowOffset = CGSize(width: 0, height: -2.0)
shadowLayer.shadowOpacity = 0.1
shadowLayer.shadowRadius = 4
layer.insertSublayer(shadowLayer, at: 0)
}
}
不幸的是,这仅隐藏了顶角,但如果 View 是按钮,它们仍然可以单击。
关于swift - 添加阴影以仅用两个带半径的角进行 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59952785/