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

标签 ios math drawing geometry core-graphics

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

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

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

enter image description here

最佳答案

以下代码计算长度为 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 重复上次的计算。

关于ios - 如何使用 Core Graphics 在 iOS 中计算和绘制尺寸线(具有垂直端线的线)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18024657/

相关文章:

ios - 为什么我会收到此错误 : fatal error - array index out of range?

algorithm - 两个数组是相互排列的吗?

javascript - 在 javascript/typescript 中绘制形状并填充颜色

opengl - 在 OpenGL 中,背景对象绘制在前景对象的前面?

ios - 如何在空数组的基础上更改 UItableview 中的 NumberOfRowsInSection

ios - 内容 View 自动布局

ios - 按下通话按钮时关闭 CNContactPickerViewController

python - 确定多组整数的交集是否非空的最快方法是什么?

java - 将两个数组对象相加

C#填充多边形(三角形)