Swift 绘制虚线

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)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容