如何使用另外两个点及其角度找到第三个点

时间:2011-10-15 20:17:11

标签: objective-c quartz-graphics

我在这里找到了答案,但无法理解如何将数学转移到Objective C

Find the third point

我有两个点,我也有相对于轴的角度。如何找到形成直线的第三个点?距离应该是可变的。

2 个答案:

答案 0 :(得分:3)

这是我正在使用的代码:

float distanceFromPx2toP3 = 1300.0;    

float mag = sqrt(pow((px2.x - px1.x),2) + pow((px2.y - px1.y),2));
float P3x = px2.x + distanceFromPx2toP3 * (px2.x - px1.x) / mag;
float P3y = px2.y + distanceFromPx2toP3 * (px2.y - px1.y) / mag;

CGPoint  P3 = CGPointMake(P3x, P3y);

答案 1 :(得分:2)

假设我有两点pointA和pointB。由两个点m形成的线的斜率是:

static CGFloat calculateSlope(CGPoint pointA, CGPoint pointB) {
  CGFloat m = (pointB.y - pointA.y) / (pointB.x - pointA.x);
  return m;
}

第三个点C与线上的点A的距离d将由下式给出:

static CGPoint calculatePointOnLine(
  CGPoint pointA, CGPoint pointB, CGFloat d, BOOL startAtB) {

  CGFloat m = calculateSlope(pointA, pointB);

  CGFloat dX = pointB.x - pointA.x;
  CGFloat dY = pointB.y - pointA.y;

  CGFloat signDX = dX / fabsf(dX);
  CGFloat signDY = dY / fabsf(dY);

  CGFloat dSquared = d * d;
  CGFloat mSquared = m * m;

  // We know pointC is distance d from pointA,
  // and that pointA and pointC are on the
  // same line
  // dXSquared + dYSquared = dSquared
  // m = dY / dX
  // dY = m * dX
  // dXSquared + mSquared * dXSquared = dSquared
  // dXSquared * ( 1 + mSquared ) = dSquared
  // dXSquared = dSquared / ( 1 + mSquared )

  // Handle a vertical line, dX == 0, and a horizontal line, dY == 0
  if (dX != 0 && dY != 0) {
    // Account for the sign of dX
    dX = signDX * sqrtf(dSquared / ( 1 + mSquared ));

    // Account for the sign of dY
    dY = signDY * m * dX;
  }

  // Handle a vertical line, dX == 0
  if (dX == 0 && dY != 0) {
    dY = signDY * d;
  }

  // Handle a horizontal line, dY == 0
  if (dY == 0 && dX != 0) {
    dX = signDX * d;
  }

  CGPoint startingPoint = pointA;
  if (startAtB) {
    startingPoint = pointB;
  }

  CGPoint pointC = CGMakePoint(startingPoint.x + dX, 
                               startingPoint.y + dY);
  return pointC;
}

pointC现在总是位于距离点A的线的距离d, 在从pointA到pointB的方向上。将startAtB传递给pointC 沿着从B点开始的直线距离为d pointA到pointB。

在对calculatPointOnLine的调用中交换piintA和pointB的顺序 计算沿着该线的距离d的pointC PointB,从pointB到pointA的方向。

您可以使用这两个函数计算线上的第三个点。 如果这对你有所帮助,感谢你接受这个答案。