2011-10-15 45 views

回答

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); 
+0

你的回答幫了我很多......謝謝 –

2

假設我有兩點pointA和pointB。由兩個點米形成的線的斜率是:

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

第三點pointC從點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的線 從點A到點B的方向的距離d。通過startAtB讓pointC 位於沿着從點B的線的距離d,從 pointA到pointB的方向。

交換piintA和pointB的在調用calculatPointOnLine 的爲了計算pointC其位於距離d沿從 PointB線,在從pointB至點A的方向。

您可以使用這兩個函數來計算線上的第三個點。 感謝您接受這個答案,如果這可以幫助你。

+0

感謝您的回答! 我想比較我和你的代碼... ' - (float)calculateAngle:(float)x1 y1:(float)y1 x2:(float)x2 y2:(float)y2 { float x = x2-x1; float y = y2-y1; (atan2(-x,-y)*(180/M_PI)); 返回角度; }' 這將返回第三點我有這樣的事情的角度正確 ,但看起來像它不工作 '浮MAG =開方((px2.x - px1.x)* 2 +(px2.y - px1.y)* 2); float P3x = px2.x + 100 *(px2.x - px1.x)/ mag; float P3y = px2.y + 100 *(px2.y - px1.y)/ mag;' –

+0

我確實嘗試了您的代碼,但它只是以積極的方式工作。任何想法該怎麼做,以便此代碼工作360? –

+0

該功能現在應考慮負面的角度和負面。它也將處理水平線和垂直線 –

相關問題