0

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

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

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

在此处输入图像描述

4

1 回答 1

5

下面的代码计算一个长度为 1 的向量,该向量垂直于从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);

现在,您在第一个点上添加和减去该垂直向量的倍数,以获得第一条标记线的端点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);

对于第二条标记线,只需使用p1而不是重复最后一次计算p

于 2013-08-02T19:39:52.090 回答