我正在尝试使用图层和渐变为视图添加阴影。遵循我能够实现的目标:
1)路径
let path = UIBezierPath()
path.move(to: CGPoint(x: myView.frame.minX, y: myView.frame.minY))
path.addLine(to: CGPoint(x: myView.frame.minX, y: myView.frame.maxY))
path.addLine(to: CGPoint(x: myView.frame.maxX, y: 171))
path.addLine(to: CGPoint(x: myView.frame.maxX, y: myView.frame.minY))
path.close()
2)形状
let shape = CAShapeLayer()
shape.path = path.cgPath
3)渐变和阴影
let gradient = CAGradientLayer()
gradient.frame = myView.bounds
gradient.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1, y: 1)
let shadow = CALayer()
shadow.shadowPath = path.cgPath
shadow.shadowColor = UIColor.black.cgColor
shadow.shadowOffset = CGSize.zero
shadow.shadowOpacity = 0.5
4)将所有图层作为我视图的子图层
self.myView.layer.addSublayer(shape)
self.myView.layer.addSublayer(gradient)
self.myView.layer.addSublayer(shadow)
self.myView.layer.mask = shape
这里有什么模拟器给我看:什么?!?!阴影放在视图上,而不是下面!
我该怎么办才能修复它?我的最终目的是将阴影置于视图下方(如红线所示)。
答案 0 :(得分:0)
您也应该指定阴影半径。
shadow.shadowRadius = 5
答案 1 :(得分:0)
3)将形状设置为渐变的蒙版。将阴影设置为myView.layer
let gradient = CAGradientLayer()
gradient.frame = myView.bounds
gradient.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1, y: 1)
gradient.mask = shape // <-- 1
let shadow = myView.layer // <-- 2
shadow.shadowPath = path.cgPath
shadow.shadowColor = UIColor.black.cgColor
shadow.shadowOffset = CGSize.zero
shadow.shadowOpacity = 0.5
4)只需将渐变作为myView.layer
self.myView.layer.addSublayer(gradient) // <-- 3