【问题标题】:How to Calculate and Draw Dimension Line (line with perpendicular end lines) in iOS using Core Graphics?如何使用 Core Graphics 在 iOS 中计算和绘制尺寸线(带有垂直端线的线)?
【发布时间】:2013-08-02 19:22:13
【问题描述】:

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

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

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

【问题讨论】:

    标签: ios math drawing geometry core-graphics


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      • 2015-04-04
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多