使用UIBezierPath(IOS)绘制带有2个CGPoint的Ray

问题描述 投票:1回答:2
UIBezierPath *myPath = [[UIBezierPath bezierPath];
[myPath moveToPoint: firstPoint];
[myPath addLineToPoint: secondPoint];
myPath.lineWidth = 10;
[[UIColor yellowColor]setStroke];
[myPath stroke];

当我运行此代码时,它会自然地绘制一个段(从1点到另一点)。我试图找到一种绘制光线的方法。我的意思是从“firstPoint”到“secondPoint”直到屏幕结束。我不介意光点是否永远持续(我猜)。

这就是它的样子。

enter image description here

谢谢。

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

ios objective-c uibezierpath raytracing
2个回答
3
投票

您可以使用公式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];

2
投票

从第二个点中减去第一个点以获得光线的方向向量:

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];
© www.soinside.com 2019 - 2024. All rights reserved.