一些 cornerRadius 的 shadowPath 错误

Wrong shadowPath for some cornerRadius

发现在某些边缘情况下,shadowPath 似乎使阴影过于圆润。

我正在对所有子视图应用相同的阴影设置,我希望具有与视图相同的角半径的 UIBezierPath 的行为相同。但似乎当高度开始下降时,它们的行为有所不同。

知道为什么或如何解决它吗?

现在,我为 UIBezierPath cornerRadius 添加了一个校正器,它有点工作,但感觉不是正确的解决方案。

    var cornerRadiusFix: CGFloat = cornerRadius
    if cornerRadiusFix > subView.bounds.height / 3 {
        cornerRadiusFix = cornerRadiusFix * 0.8
    }

    subView.layer.shadowPath = UIBezierPath(roundedRect: subView.bounds, cornerRadius: cornerRadiusFix).cgPath

尝试类似的东西

var cornerRadius: CGFloat = 32.0
let layerHalfHeight = subView.bounds.height / 2.0
if layerHalfHeight < cornerRadius {
    cornerRadius = layerHalfHeight
}

subView.layer.cornerRadius = cornerRadius

let path = UIBezierPath()
path.move(to: CGPoint(x: cornerRadius, y: 0.0))
path.addLine(to: CGPoint(x: subView.bounds.width - cornerRadius, y: 0.0))
path.addArc(withCenter: CGPoint(x: subView.bounds.width - cornerRadius, y: cornerRadius), radius: cornerRadius, startAngle: 3.0 * .pi / 2.0, endAngle: 2 * .pi, clockwise: true)
path.addLine(to: CGPoint(x: subView.bounds.width, y: subView.bounds.height - cornerRadius))
path.addArc(withCenter: CGPoint(x: subView.bounds.width - cornerRadius, y: subView.bounds.height - cornerRadius), radius: cornerRadius, startAngle: 0.0, endAngle: .pi / 2.0, clockwise: true)
path.addLine(to: CGPoint(x: cornerRadius, y: subView.bounds.height))
path.addArc(withCenter: CGPoint(x: cornerRadius, y: subView.bounds.height - cornerRadius), radius: cornerRadius, startAngle: .pi / 2.0, endAngle: .pi, clockwise: true)
path.addLine(to: CGPoint(x: 0.0, y: cornerRadius))
path.addArc(withCenter: CGPoint(x: cornerRadius, y: cornerRadius), radius: cornerRadius, startAngle: .pi, endAngle: 3.0 * .pi / 2.0, clockwise: true)
path.close()
subView.layer.shadowPath = path.cgPath

所以主要思想是当图层的高度小于默认角半径 * 2 时,您需要将角半径更改为高度的一半。

要使阴影路径起作用,您必须更改带有阴影的视图 UIView.layoutSubviews 中的边界。

在你的情况下,没有必要使用影子路径。只需删除设置阴影路径的行,一切都会正常工作。