UIBezierPath 有固定的数学公式, ok, 不多说, 直接拿出公式:

1
C(t) = (1 - t)^2 * P(0) + 2 * t * (1 - t) * P(1) + t^2 * P(2)

P(0) 代表起始点
P(1) 代表 control point
P(2) 代表终点

只要给出三个点, 同时 t 值, 从 0 - 1 改变, 就得到了一条曲线, 也就是我们常用的方法 addQuadCurveToPoint:controlPoint: , 既然知道公式, 我们也知道 P(0)、P(1)、P(2),只要通过 x 求出 t, 在通过 t 来回推出 y 即可.

1
2
3
4
5
6
根据上面的公式可得出:
X = (1 - t)^2 * X0 + 2 * t * (1 - t) * X1 + t^2 * X2
经过换算:
t = (X - X0) / (2 * (X1 - X0))
再把 `t` 代入下面的方程式中, 即可获得 y
Y = (1 - t)^2 * Y0 + 2 * t *(1 - t) * Y1 + t^2 * Y2

下面是具体实现, 可以直接使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* see https://stackoverflow.com/questions/26857850/get-points-from-a-uibezierpath/26858983
Given the equation
X = (1-t)^2*X0 + 2*t*(1-t)*X1 + t^2 *X2
I solve for t
t = ((2.0 * x0 - x1) + sqrt(((-2.0 * x0 + x1) ** 2.0)
- ((4 * (x0 - 2.0 * x1 + x2)) * (x0 - x)))) / (2.0 * (x0 - 2.0 * x1 + x2))
or
t = ((2.0 * x0 - x1) - sqrt(((-2.0 * x0 + x1) ** 2.0)
- ((4 * (x0 - 2.0 * x1 + x2)) * (x0 - x)))) / (2.0 * (x0 - 2.0 * x1 + x2))
Using this value, find Y that corresponds to X (we used X to find the above t value)
Y = (1-t)^2*Y0 + 2*t*(1-t)*Y1 + t^2 *Y2
*/
- (float)getYFromBezierPath:(float)x start:(CGPoint)start ctrlpt:(CGPoint)ctrlpt end:(CGPoint)end {
float y;
float t;
t = [self getTvalFromBezierPath:x x0:start.x x1:ctrlpt.x x2:end.x];
y = [self getCoordFromBezierPath:t y0:start.y y1:ctrlpt.y y2:end.y];
return y;
}
// x0 start point x, x1 control point x, x2 end point x
- (float)getTvalFromBezierPath:(float)x x0:(float)x0 x1:(float)x1 x2:(float)x2 {
float t = (x - x0) / (2 * (x1 - x0));
return t;
}
//y0 start point y, y1 control point y, y2 end point y
- (float)getCoordFromBezierPath:(float)t y0: (float)y0 y1: (float)y1 y2: (float)y2 {
return (pow((1 - t), 2) * y0) + (2 * t * (1 - t) * y1) + (pow(t, 2) * y2);
}

###by the way
比较简单的获取 control point 的方法, control point 主要是控制曲线的弯曲程度, 这个方法获取的 control point 可以满足日常绘制曲线, 但特俗的需求, 需要自定义修改

1
2
3
4
5
6
7
8
9
10
11
12
13
14
- (CGPoint)controlPointWithP1:(CGPoint)p1 p2:(CGPoint)p2 {
CGPoint point = [self centerWithP1:p1 p2:p2];
CGFloat differY = fabs(p1.y - point.y);
if (p1.y > p2.y) {
point.y -= differY;
} else {
point.y += differY;
}
return point;
}
- (CGPoint)centerWithP1:(CGPoint)p1 p2:(CGPoint)p2 {
return CGPointMake((p1.x + p2.x) / 2.0f, (p1.y + p2.y) / 2.0f);
}

参考: Get points from a UIBezierPath