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

时间:2016-02-18 05:13:44

标签: ios objective-c uibezierpath raytracing

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像素)

2 个答案:

答案 0 :(得分: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];

答案 1 :(得分: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];