我很努力的阴影添加到自定义形状。
你可以看到在右边拐角弯曲部和左侧阴影矩形形状自定形状。我使用的UIView,并添加角球开到左边。
这是我的代码至今塑造的观点正确的是:
View1.backgroundColor = .green //green color is just to see the shape well
let path = UIBezierPath(roundedRect:View1.bounds,
byRoundingCorners:[.topRight, .bottomRight],
cornerRadii: CGSize(width: self.frame.height/2, height: self.frame.height/2))
let maskLayer = CAShapeLayer()
我试图添加阴影,但是阴影不会出现。下面是我尝试添加阴影的代码:
View1.layer.masksToBounds = false
View1.layer.layer.shadowPath = maskLayer.path
View1.layer.shadowColor = UIColor.black.cgColor
View1.layer.shadowOffset = CGSize(width: 0.0, height: 3.0)
View1.layer.shadowOpacity = 0.5
View1.layer.shadowRadius = 1.0
你如何添加阴影这种形状?
您可以通过使用一个单一的UIView(shadowView),加入shapeLayer子层和设置shadowView的层阴影实现这一目标。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
@IBOutlet var shadowView: UIView!
func setup() {
// setup irregular shape
let path = UIBezierPath.init(roundedRect: shadowView.bounds, byRoundingCorners: [.topRight, .bottomRight], cornerRadii: CGSize.init(width: 20, height: 20))
let layer = CAShapeLayer.init()
layer.frame = shadowView.bounds
layer.path = path.cgPath
layer.fillColor = UIColor.white.cgColor
layer.masksToBounds = true
shadowView.layer.insertSublayer(layer, at: 0)
// setup shadow
shadowView.layer.shadowRadius = 8
shadowView.layer.shadowOpacity = 0.2
shadowView.layer.shadowOffset = CGSize.init(width: 0, height: 2.5)
shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowPath = path.cgPath
}
}
注意:
shadowView.clipToBounds
必须false
的阴影生效。layer.fillColor
,设置shadowView.backgroundColor
到.clear
。
您可以轻松地通过设置“背景”属性并取消选中“剪辑到边界”复选框实现通过界面生成器上面。