2016-02-18 68 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];