如果您指定 shadowPath 属性
shadowView.layer.shadowPath =
UIBezierPath(
roundedRect: shadowView.bounds,
cornerRadius: 10).cgPath
(或任何需要的角半径。)
它甚至可以使用 .clear backgroundColor。
请注意,您当然必须在layoutSubviews
相关视图中执行此操作。
这是一个实际的完整工作示例:
import UIKit
@IBDesignable class LonelyShadow: UIView {
let corner: CGFloat = 20
override init(frame: CGRect) {
super.init(frame: frame)
common()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
common()
}
private func common() {
backgroundColor = .clear
clipsToBounds = false
layer.shadowColor = UIColor.yourColor.cgColor
layer.shadowOffset = CGSize(width: 0, height: 25)
layer.shadowOpacity = 0.3
layer.shadowRadius = 40
}
override func layoutSubviews() {
super.layoutSubviews()
layer.shadowPath = UIBezierPath(
roundedRect: bounds, cornerRadius: corner).cgPath
}
}