使用 UIBezierPath 使用 2 个 CGPoint 绘制一条射线 (IOS)

Draw a Ray with 2 CGPoint Using UIBezierPath (IOS)

UIBezierPath *myPath = [[UIBezierPath bezierPath];
[myPath moveToPoint: firstPoint];
[myPath addLineToPoint: secondPoint];
myPath.lineWidth = 10;
[[UIColor yellowColor]setStroke];
[myPath stroke];

当我运行这段代码时,它会自然地画出一段(从1点到另一点)。我正在尝试找到一种绘制射线的方法。我的意思是从“firstPoint”到“secondPoint”绘制到屏幕末尾。我不介意光线点是否永远持续下去(我猜)。

这是它的样子。

谢谢。

(如有需要,屏幕尺寸736x414像素)

您可以使用公式计算使用两点的线的斜率 m = (y2-y1)/(x2-x1)。然后通过设置 x 并根据斜率计算 y 来计算第三个点。确保检查除以 0。

y3 = m (x3-x2) + y2

将 x3 作为屏幕宽度,在您的情况下为 414。 y1 是 firstPoint.y,x2 是 secondPoint.x 等等。

示例代码

CGPoint firstPoint = CGPointMake(50, 150);
CGPoint secondPoint = CGPointMake(100, 250);
CGPoint screenMax = CGPointMake(414,736);
CGPoint lastPoint = CGPointZero;
CGFloat slope = 1.0;
if (secondPoint.x != firstPoint.x) {
    slope = (secondPoint.y - firstPoint.y) / (secondPoint.x - firstPoint.x);
    lastPoint = CGPointMake(screenMax.x, slope * (screenMax.x-secondPoint.x)+secondPoint.y);
} else {
    slope = 0;
    lastPoint.x = secondPoint.x;
    lastPoint.y = screenMax.y;
}
UIBezierPath *myPath = [UIBezierPath bezierPath];
[myPath moveToPoint: firstPoint];
[myPath addLineToPoint: secondPoint];
myPath.lineWidth = 10;
[[UIColor yellowColor]setStroke];
[myPath stroke];

//this is the extension from the second point to the end of the screen
[myPath addLineToPoint: lastPoint];
[myPath stroke];

第二点减去第一点得到射线的方向向量:

CGPoint direction = CGPointMake(secondPoint.x - firstPoint.x, secondPoint.y - firstPoint.y);

计算方向向量的大小:

CGFloat magnitude = hypot(direction.x, direction.y);

使用大小将方向向量缩放到足够大的长度;假设 4000 点:

if (magnitude == 0) {
    magnitude = 1;
}
CGFloat factor = 4000 / magnitude;
direction.x *= factor;
direction.y *= factor;

将缩放后的方向向量添加到第一个点,得到沿射线的远点:

CGPoint farPoint = CGPointMake(firstPoint.x + direction.x, firstPoint.y + direction.y);

使用第一个点和远点绘制射线:

UIBezierPath *myPath = [[UIBezierPath bezierPath];
[myPath moveToPoint:firstPoint];
[myPath addLineToPoint:farPoint];
myPath.lineWidth = 10;
[[UIColor yellowColor] setStroke];
[myPath stroke];