正在尝试向视图添加阴影。目前我有一个按钮和一个UIView,其中UIView在按钮后面,并且与按钮具有相同的框架。 UIView的约束是button的[顶部,底部,前导,尾随]。
添加阴影的代码如下:
func applySketchShadow(color: UIColor = .black, alpha: Float = 0.5,
x: CGFloat = 0, y: CGFloat = 2, blur: CGFloat = 4, spread: CGFloat = 0, bgColor: UIColor = .white){
let shadowLayer = CAShapeLayer()
shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: self.bounds.height/2).cgPath
shadowLayer.fillColor = bgColor.cgColor
shadowLayer.shadowColor = color.cgColor
if spread == 0 {
shadowPath = nil
} else {
let dx = -spread
let rect = bounds.insetBy(dx: dx, dy: dx)
shadowPath = UIBezierPath(rect: rect).cgPath
}
shadowLayer.shadowOffset = CGSize(width: x, height: y)
shadowLayer.shadowOpacity = alpha
shadowLayer.shadowRadius = blur / 2.0
self.insertSublayer(shadowLayer, at: 0)
self.layoutIfNeeded()
self.setNeedsLayout()
}
我正在tableview单元中调用此代码,该单元具有上述按钮和视图。我在调用tableview单元格函数的代码如下:
扩展GradientButtonCell {
func initCell(topColor : UIColor , bottomColor : UIColor , text : String , orientation : GradientOrientation , textColor : UIColor){
self.gradientButton.applyGradient(
withColours: [topColor , bottomColor],
gradientOrientation: orientation
)
self.gradientButton.setTitleColor(textColor, for: .normal)
self.gradientButton.setTitle(text, for: .normal)
self.gradientButton.titleLabel?.font = UIFont().nexaBold(withSize: 14.0)
self.gradientButton.layer.masksToBounds = true
self.gradientButton.layer.cornerRadius = self.gradientButton.frame.height/2
self.shadowView.layer.applySketchShadow(
color: UIColor.hotPink60,
alpha: 0.6,
x: 0,
y: 2,
blur: 15,
spread: -20
)
}
}
但是由于某些原因,阴影层会不断超出图像所示的范围。
任何有关如何纠正此问题的想法都将受到赞赏。
答案 0 :(得分:1)
添加UIView的此扩展名:
extension UIView {
func addShadow(
backgroundColor: UIColor = .white,
cornerRadius: CGFloat = 5,
shadowOpacity: Float = 1,
shadowRadius: CGFloat = 2,
shadowColor: UIColor = .lightGray,
shadowOffset: CGSize = CGSize(width: 1, height: 1)
) {
self.backgroundColor = backgroundColor
self.layer.masksToBounds = false
self.layer.cornerRadius = cornerRadius
self.layer.shadowOpacity = shadowOpacity
self.layer.shadowRadius = shadowRadius
self.layer.shadowColor = shadowColor.cgColor
self.layer.shadowOffset = shadowOffset
}
}
然后尝试调用这样的内容
self.shadowView.addShadow(
backgroundColor: .blue,
cornerRadius: 10,
shadowOpacity: 0.7,
shadowRadius: 5,
shadowColor: .lightGray,
shadowOffset: .zero
)