drawing dashed line using CALayer

后端 未结 8 1417
执笔经年
执笔经年 2020-12-04 16:49

I was able to draw a dashed box, using the following code:

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
CGRect shapeRect = CGRectMake(0.0f, 0.0f, 200.0f,         


        
8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 17:45

    Try this code, it works for me,

    Swift 3.0

    extension UIView {
        func addDashedLine(strokeColor: UIColor, lineWidth: CGFloat) {
    
            backgroundColor = .clear
    
            let shapeLayer = CAShapeLayer()
            shapeLayer.name = "DashedTopLine"
            shapeLayer.bounds = bounds
            shapeLayer.position = CGPoint(x: frame.width / 2, y: frame.height / 2)
            shapeLayer.fillColor = UIColor.clear.cgColor
            shapeLayer.strokeColor = strokeColor.cgColor
            shapeLayer.lineWidth = lineWidth
            shapeLayer.lineJoin = kCALineJoinRound
            shapeLayer.lineDashPattern = [4, 4]
    
            let path = CGMutablePath()
            path.move(to: CGPoint.zero)
            path.addLine(to: CGPoint(x: frame.width, y: 0))
            shapeLayer.path = path
    
            layer.addSublayer(shapeLayer)
        }
    }
    

提交回复
热议问题