我知道如何使用Core Graphics绘制简单的线条。我现在需要绘制尺寸线以进行测量。请参阅下图,了解我需要绘制的示例(红色)。顶线很容易,但是在对角线上绘制垂线将需要一些数学计算,我现在很难搞清楚。
每条主线将以(x,y)为起点,(x1,y1)为终点。然后我需要绘制在每个点(x,y)和(x1,y1)处相交的垂直线。
计算这些垂直线的点所需的数学是什么?
答案 0 :(得分:4)
以下代码计算长度为1的向量,该向量垂直于
从p = (x, y)
到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
重复上一次计算。