如何拉伸点?

How to stretch points?

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

0 | 1.0 | 2.0 | 3.0 | 4

中间的点可以改变,但移动时必须拉伸其他点。

所以对于 stretch "to right",它必须 enlarge 移动点周围的前一个值和 press 移动点和最后一个点之间的下一个值, 保持每个点之间的比例。

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

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?)

谁能帮帮我?

你忘记了非零起点

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

请注意,如果起始值不为零,则应将相同的逻辑应用于之前的点

一般来说,要对初始 X0..X1 区间和最终 X0new..X1new 区间应用线性插值,必须使用

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

您在点左侧所做的(并且有效)可以这样重写:

//  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]);
}