swift- UIView实现虚线边框

1,282 阅读1分钟
实现xuextension UIView{
    /*
     width:虚线的宽度
     length:虚线的长度
     space:虚线间的间距
     cornerRadius:view圆角
     color:虚线的颜色
     */
    func drawBoardDottedLine(width:CGFloat,length:CGFloat,space:CGFloat,cornerRadius:CGFloat,color:UIColor){
          self.layer.cornerRadius = cornerRadius
          let borderLayer =  CAShapeLayer()
          borderLayer.bounds = self.bounds
          
          borderLayer.position = CGPoint(x: self.bounds.midX, y: self.bounds.midY);
          borderLayer.path = UIBezierPath(roundedRect: borderLayer.bounds, cornerRadius: cornerRadius).cgPath
          borderLayer.lineWidth = width / UIScreen.main.scale
          //虚线边框---小边框的长度
          borderLayer.lineDashPattern = [length,space]  as [NSNumber]?
          //前边是虚线的长度,后边是虚线之间空隙的长度
          borderLayer.lineDashPhase = 0.1
          //实线边框
          
          borderLayer.fillColor = UIColor.clear.cgColor
          borderLayer.strokeColor = color.cgColor
          self.layer.addSublayer(borderLayer)
     }
}