ios - 使用UIBezierPath(IOS)用2 CGPoint绘制光线

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

最佳答案

您可以使用公式使用两点计算线的斜率
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/

相关文章:

objective-c - StoreKit Framework "no such File or directory"导入

ios - 使用两个持久存储协调器进行高效后台更新的陷阱

iphone - 如何使用 UIBezierPath 在 Cocoa Touch 中绘制多边形

ios - 在 Swift 中将 PaintCode 代码插入 UIImageView

ios - 如何根据百分比制作圆圈?

ios - 如何缩放 UIVIew 以适应 a4 纸张大小

ios - 在 iPhone X 上测试时应用程序崩溃,但模拟器运行正常, "EXC_BAD_ACCESS"是什么

ios - 代码 : Text Field to String

ios - 解释 glReadPixels()

ios - 如何在函数外更改字典中的 Double 值?