如何伸展点?

时间:2017-04-19 10:20:11

标签: c++ algorithm stretching

假设我有5个点,其中p0和p4固定为值0.0和4.0:

0 | 1.0 | 2.0 | 3.0 | 4

中间的点可以改变,但是一旦移动它们就必须拉伸其他点。

因此,对于stretch“向右”,它必须enlarge移动点周围的prev值,press移动点和最后一点之间的下一个值,保持每个点之间的比例。

我写了这个code,它将3°点移动到原始2.5 x位置的2.0

const int numPoints = 5;
double points[numPoints] = { 0.0, 1.0, 2.0, 3.0, 4.0 };

int stretchedPoint = 2;
double prevX = points[stretchedPoint];
points[stretchedPoint] = 2.5;

std::cout<< points[0];
for (int prevPoint = 1; prevPoint < numPoints - 1; prevPoint++) {
    // prev points
    if (prevPoint < stretchedPoint) {
        double ratio = points[stretchedPoint] / prevX;
        points[prevPoint] *= ratio;
    // next points
    } else if (prevPoint > stretchedPoint) {
        double ratio = (points[numPoints - 1] - prevX) / (points[numPoints - 1] - points[stretchedPoint]);
        points[prevPoint] *= ratio;
    }

    std::cout << " | " << points[prevPoint];
}
std::cout << " | " << points[numPoints - 1];

这给了我正确的结果为上一点:

0 | 1.25 | 2.5 | 0.76 | 4

但是当我尝试对下一个点应用“same-wrapped-math”时,我会得到一个非比例缩放,这会产生奇怪的结果(4?)

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

你忘记了非零起点

 points[prevPoint] = points[stretchedPoint] + ratio * (points[prevPoint] - prevX)

请注意,如果起始值非零,则应对previos点应用相同的逻辑

通常,要对初始X0..X1间隔和最终X0new..X1ne w间隔应用线性插值,必须使用

 (Xnew - X0new) / (X1new - X0new) = (X - X0) / (X1 - X0)
 so
 XNew = X0new + (X1new - X0new) * (X - X0) / (X1 - X0)

答案 1 :(得分:1)

你在点的左侧做了什么(哪个有效)可以这样重写:

//  double ratio = (points[stretchedPoint] - 0) / (prevX - 0);
//  points[prevPoint] = 0 + ratio * (points[prevPoint] - 0);

要在右侧完全实现双重,它应该是:

} else if (prevPoint > stretchedPoint) {
    double ratio = (points[numPoints - 1] - points[stretchedPoint]) /
         (points[numPoints - 1] - prevX);
    points[prevPoint] = points[numPoints - 1] -
        ratio * (points[numPoints-1] - points[prevPoint]);
}