繪制虛線鲸郊,水平方向與垂直方向
先看下效果圖
繪制虛線
1.水平方向
在UIView擴展里面,添加一個繪制方法
extension UIView{
//MARK:- 繪制虛線
func drawDashLine(strokeColor: UIColor, lineWidth: CGFloat = 1, lineLength: Int = 10, lineSpacing: Int = 5) {
let shapeLayer = CAShapeLayer()
shapeLayer.bounds = self.bounds
// shapeLayer.anchorPoint = CGPoint(x: 0, y: 0)
shapeLayer.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = strokeColor.cgColor
shapeLayer.lineWidth = lineWidth
shapeLayer.lineJoin = CAShapeLayerLineJoin.round
shapeLayer.lineDashPhase = 0 //從哪個位置開始
//每一段虛線長度 和 每兩段虛線之間的間隔
shapeLayer.lineDashPattern = [NSNumber(value: lineLength), NSNumber(value: lineSpacing)]
let path = CGMutablePath()
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: self.layer.bounds.width, y: 0))
shapeLayer.path = path
self.layer.addSublayer(shapeLayer)
}
}
使用方法:
//橫線
let horizontalLineView = UIView(frame: CGRect(x: 100, y: 150, width: 200, height: 0.5))
horizontalLineView.drawDashLine(strokeColor: .red, lineWidth: 0.5, lineLength: 6, lineSpacing: 6)
self.view.addSubview(horizontalLineView)
2.垂直方向
創(chuàng)建一個JXDashLineView類
class JXDashLineView: UIView {
private var lineLength: CGFloat = 1
private var lineSpacing: CGFloat = 5
private var lineColor: UIColor!
private var lineHeight: CGFloat!
init(frame: CGRect, lineLength: CGFloat = 1, lineSpacing: CGFloat = 5, lineColor: UIColor = .black, lineHeight: CGFloat = 50) {
super.init(frame: frame)
backgroundColor = UIColor.white
self.lineLength = lineLength
self.lineSpacing = lineSpacing
self.lineColor = lineColor
self.lineHeight = frame.size.height
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
// Drawing code
let context = UIGraphicsGetCurrentContext()
context?.beginPath()
context?.setLineWidth(1)
context?.setStrokeColor(lineColor.cgColor)
let lengths = [lineLength, lineSpacing]
context?.setLineDash(phase: 0, lengths: lengths)
context?.move(to: CGPoint(x: 0, y: 0))
context?.addLine(to: CGPoint(x: 0, y: lineHeight))
context?.strokePath()
context?.closePath()
}
}
使用方法:
//豎線
let verticalLineView = JXDashLineView(frame: CGRect(x: 200, y: 200, width: 0.5, height: 200), lineLength: 4, lineSpacing: 3, lineColor: .systemPink, lineHeight: 60)
self.view.addSubview(verticalLineView)
Demo地址:https://github.com/jixiang0903/JXDashLine
如果本文幫到了您溅蛉,歡迎點贊公浪、收藏喲!4唷欠气!