【发布时间】:2019-12-21 06:51:32
【问题描述】:
我正在尝试向视图添加阴影。目前我有一个按钮和一个 UIView ,其中 UIView 位于按钮后面,与按钮具有相同的框架。 UIView 的约束是 button 的 [top, bottom,leading, trailing]。
添加阴影的代码如下:
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
)
}
}
但由于某种原因,阴影层不断超出如图所示的范围。
感谢任何有关如何纠正此问题的想法。
【问题讨论】:
标签: ios swift uitableview calayer bounds