如何使用 Core Graphics 在 iOS 中计算和绘制尺寸线(具有垂直端线的线)?

the*_*atp 0 math geometry drawing core-graphics ios

我知道如何使用 Core Graphics 绘制简单的线条。我现在需要绘制一条尺寸线进行测量。有关我需要绘制的示例(红色),请参见下图。顶线很容易,但在对角线上绘制垂直线需要一些数学运算,我现在很难弄清楚。

每条主线都以 (x,y) 作为起点,以 (x1,y1) 作为终点。然后我需要绘制在每个点 (x,y) 和 (x1,y1) 处相交的垂直线。

计算这些垂直线的点所需的数学是什么?

在此处输入图片说明

Mar*_*n R 5

下面的代码计算一个长度为 1 的向量,该向量垂直于 from p = (x, y)to的线p1 = (x1, y1)

CGPoint p = CGPointMake(x, y);
CGPoint p1 = CGPointMake(x1, y1);

// Vector from p to p1;
CGPoint diff = CGPointMake(p1.x - p.x, p1.y - p.y);
// Distance from p to p1:
CGFloat length = hypotf(diff.x, diff.y);
// Normalize difference vector to length 1:
diff.x /= length;
diff.y /= length;
// Compute perpendicular vector:
CGPoint perp = CGPointMake(-diff.y, diff.x);
Run Code Online (Sandbox Code Playgroud)

现在,您在第一个点上加上和减去该垂直向量的倍数,以获得第一条标记线的端点p

CGFloat markLength = 3.0; // Whatever you need ...
CGPoint a = CGPointMake(p.x + perp.x * markLength/2, p.y + perp.y * markLength/2);
CGPoint b = CGPointMake(p.x - perp.x * markLength/2, p.y - perp.y * markLength/2);
Run Code Online (Sandbox Code Playgroud)

对于第二个标记行,只需用p1代替重复最后一次计算p