如何将圆角半径添加到 UIView 周围的虚线边框

How add corner radius to dashed border around an UIView

我有一个圆角 UIView 并且我添加了一个虚线描边。

,,,
    var view = CAShapeLayer()
    view.strokeColor = UIColor.red.cgColor
    view.lineDashPattern = [2, 2]
    view.frame = addphotoView.bounds
    view.fillColor = nil
    view.path = UIBezierPath(rect: addphotoView.bounds).cgPath
    view.cornerRadius = 16
    view.masksToBounds = true

    addphotoView.layer.addSublayer(yourViewBorder)

但是 view.cornerRadius 没有按预期工作:

Corner is wiped out.

快速回答

您应该将 Layer 舍入 path

像这样:

borderLayer.path = UIBezierPath(roundedRect: addphotoView.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 16, height: 16)).cgPath


使用扩展更好的答案

您可以将所有这些逻辑移动到一个扩展中:

extension UIView {
    @discardableResult
    func addLineDashedStroke(pattern: [NSNumber]?, radius: CGFloat, color: CGColor) -> CALayer {
        let borderLayer = CAShapeLayer()

        borderLayer.strokeColor = color
        borderLayer.lineDashPattern = pattern
        borderLayer.frame = bounds
        borderLayer.fillColor = nil
        borderLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).cgPath

        layer.addSublayer(borderLayer)
        return borderLayer
    }
}

用法:

addphotoView.addLineDashedStroke(pattern: [2, 2], radius: 16, color: UIColor.gray.cgColor)