【Swift】虚线的绘制

swift .绘制一条虚线

        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: 60, lineSpacing: 5, lineColor: UIColor.red)
    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)
    }

【Swift】虚线的绘制_第1张图片

你可能感兴趣的:(Swift)