Swift 绘制虚线

2022-07-09  本文已影响0人  萤火驻守心间
image.png

lineLength:虚线长度
lineSpacing:虚线间的间距

private func drawDashLine(lineView : UIView,lineLength : Int ,lineSpacing : Int,lineColor : UIColor){
        let shapeLayer = CAShapeLayer()
        shapeLayer.bounds = lineView.bounds
        shapeLayer.anchorPoint = CGPoint(x: 0, y: 0)
        shapeLayer.strokeColor = lineColor.cgColor
        shapeLayer.lineWidth = 1 //描边路径时使用的线宽。默认为1。
        shapeLayer.lineJoin = CAShapeLayerLineJoin.round
        shapeLayer.lineDashPattern = [NSNumber(value: lineLength),NSNumber(value: lineSpacing)]
        let path = CGMutablePath()
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: lineView.bounds.size.width, y: 0))
        shapeLayer.path = path
        lineView.layer.addSublayer(shapeLayer)
    }

使用示例:

        let lineView = UIView()
        lineView.frame = CGRect(x: 15, y: 100, width: UIScreen.main.bounds.size.width-30, height: 1)
        view.addSubview(lineView)
        drawDashLine(lineView: lineView, lineLength: 10, lineSpacing: 5, lineColor: .orange)
上一篇下一篇

猜你喜欢

热点阅读