2010-11-02 99 views
7

我需要計算線條之間的角度。我需要計算atan。所以我用這樣的代碼有助於正確計算atan2

static inline CGFloat angleBetweenLinesInRadians2(CGPoint line1Start, CGPoint line1End) 
{ 
    CGFloat dx = 0, dy = 0; 

    dx = line1End.x - line1Start.x; 
    dy = line1End.y - line1Start.y; 
    NSLog(@"\ndx = %f\ndy = %f", dx, dy); 

    CGFloat rads = fabs(atan2(dy, dx)); 

    return rads; 
} 

但我不能超過180度((後

179度去178..160..150等等。我需要在360度旋轉我怎麼能做到這一點有什麼不對

莫比這有助於:??

//Tells the receiver when one or more fingers associated with an event move within a view or window. 
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    NSArray *Touches = [touches allObjects]; 
    UITouch *first = [Touches objectAtIndex:0]; 

    CGPoint b = [first previousLocationInView:[self imgView]]; //prewious position 
    CGPoint c = [first locationInView:[self imgView]];   //current position 

    CGFloat rad1 = angleBetweenLinesInRadians2(center, b); //first angel 
    CGFloat rad2 = angleBetweenLinesInRadians2(center, c); //second angel 

    CGFloat radAngle = fabs(rad2 - rad1);   //angel between two lines 
    if (tempCount <= gradus) 
    { 
     [imgView setTransform: CGAffineTransformRotate([imgView transform], radAngle)]; 
     tempCount += radAngle; 
    } 

} 

回答

5

取出fabs電話,簡單地使其:

CGFloat rads = atan2(dy, dx); 
+0

我嘗試了。不工作 – yozhik 2010-11-02 17:11:13

+0

@yozhik:也許你應該去明白什麼是行不通的。預期的結果是什麼?你看到了什麼? – casablanca 2010-11-02 17:14:39

+0

我有一個十進制座標系。我正在拍攝照片。有成像零。當我在180度以上拍攝並移動我的照片時 - 一切盡在掌握。當我試圖移動180度,例如190度時,它會顯示170度。我需要那裏190度。你看...... – yozhik 2010-11-02 17:24:49

7

atan2返回結果在[-180,180](或-pi,弧度PI)爲了從0,360使用效果:

float radians = atan2(dy, dx); 
if (radians < 0) { 
    radians = TWO_PI + radians; 
} 

應該指出,這是典型的表達[-pi,PI]轉正是如此,你可以只使用atan2結果,而無需擔心的跡象。

+0

不工作:( – yozhik 2010-11-02 17:11:32

+0

我編輯我的問題,莫比它有助於獲得什麼是錯。 – yozhik 2010-11-02 17:12:07

+0

什麼沒」我想你用'TWO_PI'取代了一個適當的常數 – 2010-11-02 17:27:41

0

使用此功能在斯威夫特。這確保從「fromPoint」到「toPoint」的角度在0到< 360之間(不包括360)。請注意,以下函數假定CGPointZero位於左上角。

func getAngle(fromPoint: CGPoint, toPoint: CGPoint) -> CGFloat { 
    let dx: CGFloat = fromPoint.x - toPoint.x 
    let dy: CGFloat = fromPoint.y - toPoint.y 
    let twoPi: CGFloat = 2 * CGFloat(M_PI) 
    let radians: CGFloat = (atan2(dy, -dx) + twoPi) % twoPi 
    return radians * 360/twoPi 
} 

。對於其中原點在左下角的情況下

let twoPi = 2 * Float(M_PI) 
let radians = (atan2(-dy, -dx) + twoPi) % twoPi 
let angle = radians * 360/twoPi