我想用NSBezierPath画一个正方形。正方形的边框必须停止,所以我使用 dashStyle,但我无法控制创建的段数。
在Apple文档中,解释有点模糊。他们说:"设置线虚线图案时,您可以指定每个连续实心或透明色板的宽度(以磅为单位)。 所以我想,我需要一种方法来获得弯曲贝塞尔的长度。
有谁知道我如何实现这一目标?
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
}
}
}
通过这个扩展,我得到了贝塞尔的"近似"长度。之后,一切都很简单:
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()