线细分算法

时间:2012-07-16 08:02:38

标签: java algorithm geometry vector-graphics

我试图在任意数量的段的弧上绘制刻度线。弧是GeneralPath对象。

我想在弧上绘制 n 刻度线(其中n是算法的输入)。我还需要在弧的开始和结束处画一个勾号。

有没有人能指出我能在哪里找到这样的算法?

2 个答案:

答案 0 :(得分:1)

嗯,一条线是一个2D矢量。取它的方向,得到长度,除以n,然后使用起点,方向向量和开始与刻度之间的距离计算刻度的位置。

编辑:

也有一些伪代码:

double unnormalizedDir.x = end.x - start.x;
double unnormalizedDir.y = end.y - start.y;

double length = sqrt(unnormalizedDir.x * unnormalizedDir.x + unnormalizedDir.y * unnormalizedDir.y );

double dir.x = unnormalizedDir.x / length;
double dir.y = unnormalizedDir.y / length;

double tickLength = length / n;

for( int i = 1; i <= n; i++ ) {
  double tick.x = start.x + dir.x * i * ticklength;
  double tick.y = start.y + dir.y * i * ticklength;    
}

这应该为您提供线上刻度线的位置。请注意,您可能应该将计算放入表示2D矢量的类中 - 或者更好,使用现有的几何库。

更新

由于您使用GeneralPath此方法仅适用于部分。 我目前无法想出一个聪明的算法,但你总是可以将路径段视为线或弧并迭代它们。然后,刻度之间的距离将是路径长度除以n,路径长度将是各个部分长度的总和。

然后遍历切片并且如果在两个刻度之间存在顶点(段的起点/终点),则计算该顶点到最后刻度的距离并使用该顶点的距离来启动上述算法下一个刻度。

类似的东西:

double distToNextTick = pathLength / n;
double distLastTickToNextVertex = ... ; //calculate
while( distToNextTick > distLastTickToNextVertex ) {
   Point2D nextVertex = ... // get the vertex
   distToNextTick -= distLastTickToNextVertex;

   distLastTickToNextVertex = ...;// calculate again
}

if( distToNextTick == 0.0 ) {
  //the tick is exactly on a vertex
}
else {
  //the tick is on the segment starting at the last vertex
  //for straight lines calculate as above
  //for curves use an appropriate algorithm (depending on the type of curve)
}

答案 1 :(得分:1)

你真的想使用PathIterator(通过GeneralPath。getPath)沿构成弧线的(稍微扁平的)线段走路。您可以进行两次传递 - 一次用于计算这些线段的总长度,另一次用于实际绘制刻度线。在两次通过之间,您可以计算最接近期望的刻度长度的刻度数,同时仍然保证开头和结尾的刻度(或者您可以允许开始或结束刻度太接近其他刻度,并且那么你只需要一次通过。)

实际的绘图代码与Thomas'相似,但是当你的迭代器通过展平路径前进时会跳过段跳。

相关问题