直接上代碼
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)
}
給某個(gè)view設(shè)置虛線邊框需要再layoutSubViews中進(jìn)行疗疟,不然獲取不到該view的frame,如果使用自動(dòng)布局梭冠,需要設(shè)置該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)
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者