考虑一条从 A (x,y) 点到 B (p,q) 的直线。
方法CGContextMoveToPoint(context, x, y);
移动到点x,y,方法CGContextAddLineToPoint(context, p,q);
将绘制从 A 点到 B 点的直线。
我的问题是,我能找到这条线覆盖的所有点吗?
实际上我需要知道终点 B 之前 x 点的确切点。
引用这张图片..
以上内容仅供引用。这条线可以有任何角度。我需要位于 B 点之前的第五个点。
谢谢
最佳答案
你不应该用像素来思考。坐标是浮点值。几何点(x,y)
根本不需要是像素。事实上,您应该将像素视为坐标系中的矩形。
这意味着“终点之前的 x 像素”实际上没有意义。如果像素是矩形,则水平移动时的“x 像素”数量与垂直移动时的数量不同。如果你转向任何其他方向,就更难确定它的含义。
根据您想要做什么,将您的概念转化为像素术语可能很容易,也可能不容易。然而,最好做相反的事情,停止用像素来思考,并将当前用像素术语表达的所有内容转换为非像素术语。
还请记住,像素的确切含义取决于系统,一般来说,您可能能够也可能不能向系统查询有关它的信息(特别是如果您考虑视网膜显示器和所有与分辨率无关的功能等因素)。
编辑:
我看到您编辑了您的问题,但“点”并不比“像素”更精确。
但是我会尽力为您提供可行的解决方案。至少,一旦您以正确的方式重新表述您的问题,它将是可行的。
如果表述正确,您的问题应该是:
给定两点 A
和B
在笛卡尔空间和距离中delta
,一个点的坐标是多少 C
这样C
正在上线通过A
和B
BC段的长度为delta
?
这是该问题的解决方案:
// 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;
}
您需要确保 A 点和 B 点不要太接近,否则计算将不精确,结果将与您的预期不同。这就是epsilon
应该这样做(您可能想也可能不想更改 epsilon
的值)。
理想情况下,epsilon
的合适值与 double
中可表示的最小数字无关但达到 double
的精度水平为您提供坐标数量级的值。
我已硬编码epsilon
,这是定义其值的常见方法,因为您通常提前知道数据的数量级,但也有“自适应”技术来计算 epsilon
来自参数的实际值(在本例中为 A 和 B 的坐标以及增量)。
另请注意,我已为易读性进行了编码(编译器无论如何都应该能够优化)。如果您愿意,请随意重新编码。
关于objective-c - 如何找到一条直线上的点 - Objective c?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12617387/