Search code examples
iosswiftuibezierpath

UIBezierPath addLine: wrong length uppon draw


Given is a UIBezierPath which should be "dashed" and added to a view as a sublayer:

    let shapeLayer = CAShapeLayer()
    shapeLayer.strokeColor = UIColor.blue.cgColor
    shapeLayer.lineWidth = 0.8
    shapeLayer.lineDashPattern = [7, 7]
    shapeLayer.fillColor = UIColor.clear.cgColor

    let path = CGMutablePath()
    path.move(to: .zero)
    path.addLine(to: CGPoint(x: view.bounds.width, y: 0)) // HERE IS THE PROBLEM
    shapeLayer.path = path
    view.layer.addSublayer(shapeLayer)
    view.backgroundColor = .yellow

The problem is, that the dashed line is not equal to the width of the "view": enter image description here

The yellow is the background color of the view itself. The dashed line is the created UIBezierPath.

Thank you so much for your help.


Solution

  • If anyone stumbles on this problem:

    As @rmaddy said, the problem was that this function was being called in viewWillAppear. Where the size has not been properly initialized yet. Calling the same function in viewDidAppear solved the problem.