这需要多普遍?另外,如何表示您的形状和点?你的算法似乎没问题;您需要帮助将其转换为代码吗?
好的,这是我想出的东西。代码注释:
- distance 方法接受两个 Points 并返回它们之间的距离。
- normalize 方法取两个点并返回从第一个点指向第二个点的法线向量。
- Point 类具有将点乘以标量的 multiply 方法
- Point 类具有浮点(或双精度)精度
顺便说一下,我正在使用 Point 类来表示向量。
我没有测试过这个,所以可能有错误。该算法如何处理精确区域可能存在问题(例如,您的正方形上正好有 4 个点)。如果有问题或有任何疑问,请告诉我!:)
Point[] shapePoints; //already initialized
int numPoints; //already initialized
Point[] retPoints = new Point[numPoints];
int totalLength;
for(int i = 1; i < shapePoints.length; i++){
totalLength += distance(shapePoints[i], (shapePoints[i-1]));
}
float segLength = ((float) totalLength) / numPoints);
Point currShape = shapePoints[0];
Point nextShape = shapePoints[1];
Point prev = currShape;
int counter = 2;
while(numPoints > 0){
Point norm = normalize(new Point(nextShape.x - currShape.x, nextShape.y - currShape.y));
if(distance(nextShape, prev) < segLength){
int tempLength = segLength;
tempLength -= distance(nextShape, prev);
currShape = nextShape;
nextShape = shapePoints[counter];
counter ++;
norm = normalize(new Point(nextShape.x - currShape.x, nextShape.y - currShape.y));
norm.multiply(tempLength);
}
else{
norm.multiply(segLength);
}
retPoints[numPoints - 1] = norm;
prev = retPoints[numPoints - 1];
numPoints --;
}
Point normalize(Point p){
int scale = Math.sqrt(p.x * p.x + p.y * p.y);
p.x = p.x / scale;
p.y = p.y / scale;
return p;
}