2016-02-18 62 views
1
UIBezierPath *myPath = [[UIBezierPath bezierPath]; 
[myPath moveToPoint: firstPoint]; 
[myPath addLineToPoint: secondPoint]; 
myPath.lineWidth = 10; 
[[UIColor yellowColor]setStroke]; 
[myPath stroke]; 

当我运行此代码时,它自然会绘制一段(从1点到另一个)。我试图找到一种方法来绘制一缕曙光。我的意思是通过“secondPoint直到屏幕年底从“罗克韦尔FirstPoint”画画。我不介意,如果射线点那张永远(我猜)。使用UIBezierPath(IOS)绘制具有2个CGPoint的光线

这会是什么样子。

enter image description here

谢谢。

(如果你需要它,屏幕大小736x414像素)

回答

2

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

使用第一点和远点绘制ray:

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