0

I want to draw a square, with NSBezierPath. The border of square must to be discontinue so i use dashStyle, but I don't have any control on numbers of segments created.

On Apple documentation the explanation is a bit vague. They said that "When setting a line dash pattern, you specify the width (in points) of each successive solid or transparent swatch". So i think, I need a way to get the length of a curved bezier.

Does anyone have an idea how i can achive that ?

C-Viorel
  • 1,801
  • 3
  • 22
  • 41

1 Answers1

0
extension NSBezierPath {

    var lenght:Double {
        get{
            let flattenedPath =  self.bezierPathByFlatteningPath
            let segments = flattenedPath.elementCount
            var lastPoint:NSPoint = NSZeroPoint
            var point:NSPoint = NSZeroPoint
            var size :Double = 0

            for i in 0...segments - 1 {
                let e:NSBezierPathElement = flattenedPath.elementAtIndex(i, associatedPoints: &point)
                if e == .MoveToBezierPathElement {
                    lastPoint = point
                } else {
                    let distance:Double = sqrt(pow(Double(point.x - lastPoint.x) , 2) + pow(Double(point.y - lastPoint.y) , 2))
                   size += distance
                    lastPoint = point
                }
            }

            return size
        }
    }
}

With this extension i get the "approximative" length of a bezier. After that, everything is simple:

let myPath = NSBezierPath(roundedRect:myRect, xRadius:50, yRadius:50)
let pattern = myPath.length / (numbersOfSegments * 2) // we divide the length to double of segments we need.
myPath.setLineDash([CGFloat(pattern),CGFloat(pattern)], countL:2 , phase: 0)
myPath.stroke()
C-Viorel
  • 1,801
  • 3
  • 22
  • 41