是否有替代CGPath允许计算给定位置的路径上的点? [英] Is there an alternative to CGPath which allows to compute points on a path for a given location?

查看:146
本文介绍了是否有替代CGPath允许计算给定位置的路径上的点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于动画计时算法,我需要提供一条路径作为曲线。可能是两端都有控制点的bezier曲线。

For an animation timing algorithm I need to supply a path as the curve. Probably a bezier curve with control points on both ends.

问题是似乎无法计算CGPath上的点,因为CGPathRef是不透明的。 Apple也没有提供计算路径上的点的机制。

The problem is that it seems not possible to calculate points on a CGPath because CGPathRef is opaque. Also Apple provides no mechanism to compute points on a path.

是否有一个库或实用程序类可以计算贝塞尔曲线或路径上的点,对于给定的位置,如路径中间为0.5?

Is there a library or utility class which can compute points on a bezier curve or path, for a given location like 0.5 for the middle along the path?

或者让我改一下:如果CGPath / CGPathRef使得这不可能,因为它是不透明的,如果你只关心贝塞尔曲线,有没有办法计算路径上的位置点?

Or let me rephrase it: If CGPath / CGPathRef makes this impossible because it is opaque, and if you only care about bezier curves, is there a way to compute points for locations along the path?

推荐答案

Bézier路径背后的数学实际上是只是:

The math behind a Bézier path is actually "just":


start⋅(1-t) 3 +3⋅c 1 ⋅ t(1-t) 2 +3⋅c 2 ·t 2 (1-t)+end⋅t 3

start⋅(1-t)3 + 3⋅c1⋅t(1-t)2 + 3⋅c2⋅t2(1-t) + end⋅t3

这意味着如果你知道,开始,结束和两个控制点(c 1 和c 2 ),然后你可以计算任何t的值(从0到1)。

This means that if you know, the start, the end and both control points (c1 and c2), then you can calculate the value for any t (from 0 to 1).

它的值是点数(如下图所示)那么你可以做分别为x和y计算。

It the values are points (like in the image below) then you can do these calculations separately for x and y.

这是我在这里对Bézier路径的解释以及滑块更改(在Javascript中)更新橙色圆圈的代码就是这样(将它转换为Objective-C或简称为C而不是太难太懒了):

This is form my explanation of Bézier paths here and the code to update the orange circle as the slider changes (in Javascript) is simply this (it shouldn't be too hard to translate into Objective-C or simply C but I was too lazy):

var sx = 190; var sy = 80; // start
var ex = 420; var ey = 250; // end

var c1x = -30; var c1y = 350; // control point 1
var c2x = 450; var c2y = -20; // control point 2

var t = (x-minSliderX)/(maxSliderX-minSliderX); // t from 0 to 1

var px = sx*Math.pow(1-t, 3) + 3*c1x*t*Math.pow(1-t, 2) + 3*c2x*Math.pow(t,2)*(1-t) + ex*Math.pow(t, 3);
var py = sy*Math.pow(1-t, 3) + 3*c1y*t*Math.pow(1-t, 2) + 3*c2y*Math.pow(t,2)*(1-t) + ey*Math.pow(t, 3);
// new point is at (px, py)

这篇关于是否有替代CGPath允许计算给定位置的路径上的点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆