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];
关于ios - 使用UIBezierPath(IOS)用2 CGPoint绘制光线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35473345/