欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

创建一个高度为1的虚线

程序员文章站 2023-12-24 19:08:39
...
///创建一个高为1的线
    func config() {
        let lineView = UIView(frame: CGRect(x: 2, y: 300, width: self.view.frame.size.width - 4, height: 1))
        self.view.addSubview(lineView)
        drawDashLine(lineView: lineView, lineLength: 10, lineSpacing: 5, lineColor: UIColor.red)
    }
    
    /**
     *  通过 CAShapeLayer 方式绘制虚线
     *  lineView:       需要绘制成虚线的view
     *  lineLength:     线宽
     *  lineSpacing:    线间距
     **/
    func drawDashLine(lineView : UIView, lineLength : Int ,lineSpacing : Int,lineColor : UIColor){
        let shapeLayer = CAShapeLayer()
        shapeLayer.bounds = lineView.bounds
        //只要是CALayer这种类型,他的anchorPoint默认都是(0.5,0.5)
        shapeLayer.anchorPoint = CGPoint(x: 0, y: 0)
        //shapeLayer.fillColor = UIColor.blue.cgColor
        shapeLayer.strokeColor = lineColor.cgColor
        
        shapeLayer.lineWidth = lineView.frame.size.height
        shapeLayer.lineJoin = kCALineJoinRound
        
        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.frame.size.width, y: 0))
        
        shapeLayer.path = path
        lineView.layer.addSublayer(shapeLayer)
    }

 

相关标签: 虚线

上一篇:

下一篇: