更新时间:2023-11-17 14:42:28
Taken from this answer, translated to swift and altered a bit:
func getLines(xmin: CGFloat, ymin: CGFloat, xmax: CGFloat, ymax: CGFloat, x1: CGFloat, x2: CGFloat, y1: CGFloat, y2: CGFloat) -> (CGPoint, CGPoint) {
if y1 == y2 {
return (CGPoint(x: xmin, y: y1), CGPoint(x: xmax, y: y1))
}
if x1 == x2 {
return (CGPoint(x: x1, y: ymin), CGPoint(x: x1, y: ymax))
}
let y_for_xmin = y1 + (y2 - y1) * (xmin - x1) / (x2 - x1)
let y_for_xmax = y1 + (y2 - y1) * (xmax - x1) / (x2 - x1)
let x_for_ymin = x1 + (x2 - x1) * (ymin - y1) / (y2 - y1)
let x_for_ymax = x1 + (x2 - x1) * (ymax - y1) / (y2 - y1)
if ymin <= y_for_xmin && y_for_xmin <= ymax {
if xmin <= x_for_ymax && x_for_ymax <= xmax {
return (CGPoint(x: xmin, y: y_for_xmin), CGPoint(x: x_for_ymax, y: ymax))
}
if xmin <= x_for_ymin && x_for_ymin <= xmax {
return (CGPoint(x: xmin, y: y_for_xmin), CGPoint(x: x_for_ymin, y: ymin))
}
return (CGPoint(x: xmin, y: y_for_xmin), CGPoint(x: xmax, y: y_for_xmax))
}
if ymin <= y_for_xmax && y_for_xmax <= ymax {
if xmin <= x_for_ymin && x_for_ymin <= xmax {
return (CGPoint(x: x_for_ymin, y: ymin), CGPoint(x: xmax, y: y_for_xmax))
}
if xmin <= x_for_ymax && x_for_ymax <= xmax {
return (CGPoint(x: x_for_ymax, y: ymax), CGPoint(x: xmax, y: y_for_xmax))
}
return (CGPoint(x: xmin, y: y_for_xmin), CGPoint(x: xmax, y: y_for_xmax))
}
return (CGPoint(x: x_for_ymin, y: ymin), CGPoint(x: x_for_ymax, y: ymax))
}
func updateLine(){
let x1 = self.startPoint!.x
let x2 = self.endPoint!.x
let y1 = self.startPoint!.y
let y2 = self.endPoint!.y
let (start, end) = getLines(0, ymin: 0, xmax: bounds.width, ymax: bounds.height, x1: x1, x2: x2, y1: y1, y2: y2)
print(start, appendNewline: false)
print(" - ", appendNewline: false)
print(end)
// Draw main line.
self.drawLine(line: self.lineLayer!, start: start, end: end)
}
不幸的是,这还不能完全正常工作,因为在一半的情况下,用于返回正确的扩展行的返回的if-construct不会返回任何有用的东西.我将尝试现在或明天解决此问题.
Unfortunately that is not fully functional yet since in half of the cases the returned if-construct for returning the correct extended line is not returning anything useful. I will try to fix this either now or tomorrow.
但这应该可以帮助您开始
But it should get you started
编辑:如果起点和终点都在水平或垂直轴上,则似乎无法正常工作.如果它们位于不同的轴上,则可以正常工作.
Edit: seems to not be working if both the start and the endpoint would be on either the horizontal or vertical axis. it works if they are on different axes.
我又添加了三个return语句后,代码现在可以正常使用了:)
如果您查看记录的信息,您会发现绘制的线实际上精确地延伸到了边界,而没有延伸更多的距离.
If you take a look at the logged information you will see that the drawn line actually extends exactly to the bounds, not a bit further.