2012-06-30 40 views

回答

5

NSBezierPath没有精确定义它绘制哪些点,但它确实包含了定义它的片段所需的点。您可以使用elementAtIndex:associatedPoints:方法获取路径中每个向量元素的点。要获取路径中的每个点,您必须迭代所有元素并获取关联的点。对于直线,此方法将为您提供端点,但如果您记录了前一点,则可以根据需要使用任意数量的点。

对于曲线,您需要实现代码来确定曲线沿曲线找到点的路径。使用bezierPathByFlatteningPath来平坦化路径会简单得多,该路径返回一条将所有曲线转换成直线的新路径。

下面是一个将路径弄平并在结果中打印所有行的端点的示例。如果您的路径包含长直线,您将需要根据长度添加沿线的点。

NSBezierPath *originalPath; 
NSBezierPath *flatPath = [originalPath bezierPathByFlatteningPath]; 
NSInteger count = [flatPath elementCount]; 
NSPoint prev, curr; 
NSInteger i; 
for(i = 0; i < count; ++i) { 
    // Since we are using a flattened path, no element will contain more than one point 
    NSBezierPathElement type = [flatPath elementAtIndex:i associatedPoints:&curr]; 
    if(type == NSLineToBezierPathElement) { 
     NSLog(@"Line from %@ to %@",NSStringFromPoint(prev),NSStringFromPoint(curr)); 
    } else if(type == NSClosePathBezierPathElement) { 
     // Get the first point in the path as the line's end. The first element in a path is a move to operation 
     [flatPath elementAtIndex:0 associatedPoints:&curr]; 
     NSLog(@"Close line from %@ to %@",NSStringFromPoint(prev),NSStringFromPoint(curr)); 
    } 
} 
+0

谢谢。没有意识到elementAtIndex:associatedPoints:方法。但我有一个疑问。当我在bezierpathWithOvalInRect创建的bezierpath上展平路径之后尝试了元素数。我得到了一个数字17.如果每个元素只能包含一个点,我可以用17点创建一个完整的椭圆形,这怎么可能? – Rakesh

+0

这取决于使用的椭圆形和平面的大小。如果减小平坦度值,线条将创建更精确的表示,这意味着它需要更多点。 – ughoavgfhw

0

不,因为路径是基于矢量的,而不是基于像素的。您必须在CGContextRef中呈现路径,然后检查从中设置了哪些像素。但是没有内置的方法。

但是,如果您需要沿着路径移动一个矩形,您可能可以使用CALayer来完成此操作,但我并不完全知道如何操作。

相关问题