Swift中如何计算已知直线垂直线上的C、D点(B为CD中点)
计算C、D坐标并绘制线段的方案
核心思路
仅知道B是CD中点、CD长度无法唯一确定C、D位置,这里默认CD是垂直于AB的线段(这类绘图场景的常见需求),基于此推导坐标:
坐标计算步骤
- 计算AB的方向向量:
let dxAB = B.x - A.x let dyAB = B.y - A.y - 生成垂直于AB的单位向量(垂直向量有两个朝向,对应CD的两种摆放方向,选其一即可):
- 逆时针垂直方向:
(-dyAB, dxAB) - 顺时针垂直方向:
(dyAB, -dxAB)
单位化代码:
let abLength = sqrt(dxAB * dxAB + dyAB * dyAB) // 也可直接使用已知的AB距离 let unitPerpendicularX = -dyAB / abLength let unitPerpendicularY = dxAB / abLength - 逆时针垂直方向:
- 计算CD的半长(B是中点,C、D到B的距离为CD长度的一半):
let halfCDLength = cdLength / 2.0 - 推导C、D坐标:
// C点:从B向垂直方向偏移半长 let pointC = CGPoint(x: B.x + unitPerpendicularX * halfCDLength, y: B.y + unitPerpendicularY * halfCDLength) // D点:从B向相反垂直方向偏移半长 let pointD = CGPoint(x: B.x - unitPerpendicularX * halfCDLength, y: B.y - unitPerpendicularY * halfCDLength)
完整绘制代码示例
将坐标计算与你的绘制逻辑结合:
// 假设已有已知参数: let pointA = CGPoint(x: 100, y: 100) let pointB = CGPoint(x: 200, y: 200) let abDistance = sqrt(pow(pointB.x - pointA.x, 2) + pow(pointB.y - pointA.y, 2)) // 或直接用已知值 let cdLength: CGFloat = 50 // 计算C、D坐标 let dxAB = pointB.x - pointA.x let dyAB = pointB.y - pointA.y let unitPerpendicularX = -dyAB / abDistance let unitPerpendicularY = dxAB / abDistance let halfCD = cdLength / 2.0 let pointC = CGPoint(x: pointB.x + unitPerpendicularX * halfCD, y: pointB.y + unitPerpendicularY * halfCD) let pointD = CGPoint(x: pointB.x - unitPerpendicularX * halfCD, y: pointB.y - unitPerpendicularY * halfCD) // 绘制CD线段 let path = UIBezierPath() path.move(to: pointC) path.addLine(to: pointD) let shapeLayer = CAShapeLayer() shapeLayer.path = path.cgPath shapeLayer.strokeColor = UIColor.black.cgColor shapeLayer.lineWidth = 2.0 view.layer.addSublayer(shapeLayer)
补充说明
- 若需要CD朝另一个垂直方向,将
unitPerpendicularX和unitPerpendicularY替换为dyAB / abDistance和-dxAB / abDistance即可 - 若已知的AB距离是精确值,直接代入计算,无需重新计算
abDistance
内容的提问来源于stack exchange,提问作者MattCodes
相关产品推荐
相关产品推荐

