直接上代码
fileprivate func drawDashLine(_ view: UIView) {
let shapeLayer:CAShapeLayer = CAShapeLayer()
shapeLayer.bounds = view.bounds
shapeLayer.position = CGPoint(x: view.frame.width / 2, y: view.frame.height / 2)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = USColor.c302.cgColor
shapeLayer.lineWidth = 1
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineDashPhase = 0
shapeLayer.lineDashPattern = [NSNumber(value: 2), NSNumber(value: 2)]
let path:CGMutablePath = CGMutablePath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: view.frame.width, y: 0))
shapeLayer.path = path
view.layer.addSublayer(shapeLayer)
}
给某个view设置虚线边框需要再layoutSubViews中进行,不然获取不到该view的frame,如果使用自动布局,需要设置该view的width
override func layoutSubviews() {
super.layoutSubviews()
self.drawDashLine(self.lineView)
}
可以给UIView加上extension
public func drawDashLine() {
let shapeLayer:CAShapeLayer = CAShapeLayer()
shapeLayer.bounds = self.bounds
shapeLayer.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.red
shapeLayer.lineWidth = 1
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineDashPhase = 0
shapeLayer.lineDashPattern = [NSNumber(value: 2), NSNumber(value: 2)]
let path:CGMutablePath = CGMutablePath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: self.frame.width, y: 0))
shapeLayer.path = path
self.layer.addSublayer(shapeLayer)
}
网友评论