swift 画虚线-横线、竖线

绘制虚线,水平方向与垂直方向
先看下效果图


绘制虚线

1.水平方向
在UIView扩展里面,添加一个绘制方法

extension UIView{
    //MARK:- 绘制虚线
    func drawDashLine(strokeColor: UIColor, lineWidth: CGFloat = 1, lineLength: Int = 10, lineSpacing: Int = 5) {
        let shapeLayer = CAShapeLayer()
        shapeLayer.bounds = self.bounds
//        shapeLayer.anchorPoint = CGPoint(x: 0, y: 0)
        shapeLayer.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = strokeColor.cgColor
        shapeLayer.lineWidth = lineWidth
        shapeLayer.lineJoin = CAShapeLayerLineJoin.round
        shapeLayer.lineDashPhase = 0 //从哪个位置开始
        //每一段虚线长度 和 每两段虚线之间的间隔
        shapeLayer.lineDashPattern = [NSNumber(value: lineLength), NSNumber(value: lineSpacing)]
        let path = CGMutablePath()
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: self.layer.bounds.width, y: 0))
        shapeLayer.path = path
        self.layer.addSublayer(shapeLayer)
    }
}

使用方法:

 //横线
        let horizontalLineView = UIView(frame: CGRect(x: 100, y: 150, width: 200, height: 0.5))
        horizontalLineView.drawDashLine(strokeColor: .red, lineWidth: 0.5, lineLength: 6, lineSpacing: 6)
        self.view.addSubview(horizontalLineView)

2.垂直方向
创建一个JXDashLineView类

class JXDashLineView: UIView {
    private var lineLength: CGFloat = 1
    private var lineSpacing: CGFloat = 5
    private var lineColor: UIColor!
    private var lineHeight: CGFloat!

    init(frame: CGRect, lineLength: CGFloat = 1, lineSpacing: CGFloat = 5, lineColor: UIColor = .black, lineHeight: CGFloat = 50) {
        super.init(frame: frame)
        backgroundColor = UIColor.white
        self.lineLength = lineLength
        self.lineSpacing = lineSpacing
        self.lineColor = lineColor
        self.lineHeight = frame.size.height
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func draw(_ rect: CGRect) {
        // Drawing code
        let context = UIGraphicsGetCurrentContext()
        context?.beginPath()
        context?.setLineWidth(1)
        context?.setStrokeColor(lineColor.cgColor)
        let lengths = [lineLength, lineSpacing]
        context?.setLineDash(phase: 0, lengths: lengths)
        context?.move(to: CGPoint(x: 0, y: 0))
        context?.addLine(to: CGPoint(x: 0, y: lineHeight))
        context?.strokePath()
        context?.closePath()
    }
}

使用方法:

//竖线
        let verticalLineView = JXDashLineView(frame: CGRect(x: 200, y: 200, width: 0.5, height: 200), lineLength: 4, lineSpacing: 3, lineColor: .systemPink, lineHeight: 60)
        self.view.addSubview(verticalLineView)

Demo地址:https://github.com/jixiang0903/JXDashLine

如果本文帮到了您,欢迎点赞、收藏哟!!!

你可能感兴趣的:(swift 画虚线-横线、竖线)