【问题标题】:Dashed line with rounded corners [duplicate]带圆角的虚线[重复]
【发布时间】:2017-05-08 12:26:37
【问题描述】:

我正在尝试在这样的视图周围绘制带圆角的虚线:

class DashedLineView: UIView {

    override func draw(_ rect: CGRect) {

        let path = UIBezierPath(roundedRect: rect, cornerRadius: 8)

        UIColor.clear.setFill()
        path.fill()

        UIColor.red.setStroke()
        path.lineWidth = 3

        let dashPattern : [CGFloat] = [3, 3]
        path.setLineDash(dashPattern, count: 2, phase: 0)
        path.stroke()
    }
}

结果是:

如您所见,边角存在问题,您知道如何解决吗?

更新: 使用@Jon Rose answer DashedLineView 现在看起来像这样:

class DashedLineView: UIView {

    private let borderLayer = CAShapeLayer()

    override func awakeFromNib() {

        super.awakeFromNib()

        borderLayer.strokeColor = UIColor.red.cgColor
        borderLayer.lineDashPattern = [3,3]
        borderLayer.backgroundColor = UIColor.clear.cgColor
        borderLayer.fillColor = UIColor.clear.cgColor

        layer.addSublayer(borderLayer)
    }

    override func draw(_ rect: CGRect) {

        borderLayer.path = UIBezierPath(roundedRect: rect, cornerRadius: 8).cgPath
    }
}

【问题讨论】:

  • 考虑使用 CAShaperLayer 而不是 drawRect。我已经使用 CAShaperLayer 和路径实现了它,它看起来很好。
  • 你能举个例子吗?
  • 尝试将常规图层(您的视图之一)的cornerRadius 设置为路径的拐角半径。可能会修复我们形状层的角落或draw(_:) 实现。

标签: swift core-graphics uibezierpath


【解决方案1】:

我在使用 CAShapeLayer 方面有过很好的经验。例如:

let rect = CGRect.init(origin: CGPoint.init(x: 20, y: 100), size: CGSize.init(width: 200, height: 100))
let layer = CAShapeLayer.init()
let path = UIBezierPath(roundedRect: rect, cornerRadius: 8)
layer.path = path.cgPath;
layer.strokeColor = UIColor.red.cgColor;
layer.lineDashPattern = [3,3];
layer.backgroundColor = UIColor.clear.cgColor;
layer.fillColor = UIColor.clear.cgColor;
self.view.layer.addSublayer(layer);

作为奖励,几乎所有 CAShapeLayer 的属性都是可动画的,包括 lineDashPhase,这意味着您可以让它看起来像虚线在框周围移动。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多