我想用NSBezierPath绘制一个正方形。广场的边框必须停止,所以我使用dashStyle,但我不能控制创建的段数。
在Apple文档中,解释有点模糊。他们说"设置线条划线图案时,指定每个连续的实心或透明样本的宽度(以磅为单位)"。 所以我想,我需要一种方法来获得弯曲贝塞尔的长度。
有没有人知道我怎么能做到这一点?
答案 0 :(得分: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
}
}
}
通过此扩展,我获得了bezier的“近似”长度。在那之后,一切都很简单:
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()