はスイフト3例である:
func addDashedLine(layer: CALayer, dotSize: CGFloat) {
let p0 = CGPoint(x: 0, y: layer.bounds.height/2)
let p1 = CGPoint(x: layer.bounds.width, y: layer.bounds.height/2)
let path = UIBezierPath()
path.move(to:p0)
path.addLine(to:p1)
path.stroke()
let stepLength = Float(layer.bounds.width/10.0)
let dashPattern = [NSNumber(value: 0.001), NSNumber(value: stepLength)]
let shapeLayer = CAShapeLayer()
shapeLayer.frame = layer.bounds
shapeLayer.strokeColor = UIColor.red.cgColor
shapeLayer.lineWidth = dotSize
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineCap = kCALineCapRound
shapeLayer.lineDashPattern = dashPattern
shapeLayer.lineDashPhase = dotSize
shapeLayer.path = path.cgPath
layer.addSublayer(shapeLayer)
}
この例では、水平線を描画するために、単純なパスを使用します。一定量のドットで線を描く必要がある場合は、最初に線の長さを計算し、それから描きたい点の数で割ります。
用途:
override func viewDidLoad() {
super.viewDidLoad()
addDashedLine(layer: view.layer, dotSize: 3)
}
出力:
![enter image description here](https://i.stack.imgur.com/GSlaq.png)