如何找到一行中的点 - 目标c?

时间:2012-09-27 08:42:52

标签: objective-c line point cgcontextdrawimage

考虑从A点(x,y)到B(p,q)的一条线。

方法CGContextMoveToPoint(context, x, y);移动到点x,y,方法CGContextAddLineToPoint(context, p, q);将绘制从A点到B的线。

我的问题是,我可以找到该行所涵盖的所有要点吗?

实际上我需要知道在结束点B之前是x点的确切点。

参考此图片.. enter image description here

以上一行仅供参考。该线可以具有任何角度。我需要在B点之前的第5点。

谢谢

3 个答案:

答案 0 :(得分:4)

你不应该考虑像素。坐标是浮点值。 (x,y)处的几何点根本不需要是像素。实际上,您应该将像素视为坐标系中的矩形。

这意味着“结束点之前的x像素”并不真正有意义。如果像素是矩形,如果水平移动,“x像素”的数量与垂直移动时的数量不同。如果你向任何其他方向移动,那么决定它意味着什么就更难了。

根据您要做的事情,以像素字词翻译您的概念可能也可能不容易。然而,相反的做法可能会更好,并停止考虑像素,并将您目前用像素术语表达的所有内容转换为非像素术语。

还要记住像素究竟与系统有什么关系,一般来说,您可能会或可能不会查询系统(尤其是考虑到视网膜显示和所有与分辨率无关的功能)。

编辑:

我看到你编辑了你的问题,但“点数”并不比“像素”更精确。

但是我会尝试给你一个可行的解决方案。一旦你用正确的术语重新表述你的问题,至少它是可行的。

你的问题,正确制定,应该是:

在笛卡尔空间中给出两个点AB以及距离delta,点C的坐标是多少{{1} }}是在通过CA的行上,并且段BC的长度是B

以下是该问题的解决方案:

delta

您需要确保A点和B点不太靠近或计算不精确,结果会与您预期的不同。这就是// Assuming point A has coordinates (x,y) and point B has coordinates (p,q). // Also assuming the distance from B to C is delta. We want to find the // coordinates of C. // I'll rename the coordinates for legibility. double ax = x; double ay = y; double bx = p; double by = q; // this is what we want to find double cx, cy; // we need to establish a limit to acceptable computational precision double epsilon = 0.000001; if ( bx - ax < epsilon && by - ay < epsilon ) { // the two points are too close to compute a reliable result // this is an error condition. handle the error here (throw // an exception or whatever). } else { // compute the vector from B to A and its length double bax = bx - ax; double bay = by - ay; double balen = sqrt( pow(bax, 2) + pow(bay, 2) ); // compute the vector from B to C (same direction of the vector from // B to A but with lenght delta) double bcx = bax * delta / balen; double bcy = bay * delta / balen; // and now add that vector to the vector OB (with O being the origin) // to find the solution cx = bx + bcx; cy = by + bcy; } 应该做的事情(你可能想也可能不想改变epsilon的值)。

理想情况下,epsilon的合适值与epsilon中可表示的最小数字无关,但与double为您提供数量级的值的精度级别无关坐标

我有硬编码double,这是定义它的价值的常用方法,因为您通常事先知道数据的数量级,但也有“自适应”技术来计算{{1} }来自参数的实际值(在这种情况下,A和B的坐标以及delta)。

另请注意,我已经编写了易读性(编译器应该能够进行优化)。如果您愿意,请随意重新编码。

答案 1 :(得分:0)

这不是那么难,将你的片段转换为数学线表达式,x像素可以被转换为中心在B中的半径,使系统找到它们截取的位置,你得到两个解决方案,指出离A更近了。

答案 2 :(得分:0)

这是您可以使用的代码

 float distanceFromPx2toP3 = 1300.0;    

 float mag = sqrt(pow((px2.x - px1.x),2) + pow((px2.y - px1.y),2));
 float P3x = px2.x + distanceFromPx2toP3 * (px2.x - px1.x) / mag;
 float P3y = px2.y + distanceFromPx2toP3 * (px2.y - px1.y) / mag;

 CGPoint  P3 = CGPointMake(P3x, P3y);

您可以点击此链接,它也会为您提供详细说明 -

How to find a third point using two other points and their angle

您可以找到想要查找的点数。

相关问题