2012-07-18 72 views
1

以下是在觸摸事件中旋轉箭頭(uiimage)的代碼。在這個我減去兩個觸摸前一個和當前的位置,但問題是箭頭(uiimage)有時在觸摸的相反方向移動。如何在iphone中速度計中旋轉圖像

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event 
{ 
    UITouch *touch = [touches anyObject];   
    NSLog(@"%@",[touch view]); 
    if ([touch view] == ImgViewArrowImage) 
    { 
    CGPoint currentLocation = [touch locationInView:touch.view]; 
    CGPoint pastLocation = [touch previousLocationInView:touch.view]; 

    CGPoint d1 = CGPointMake(currentLocation.x-touch.view.center.x, currentLocation.y-touch.view.center.y); 
    CGPoint d2 = CGPointMake(pastLocation.x-touch.view.center.x, pastLocation.y-touch.view.center.y); 

    CGFloat angle1 = atan2(d1.y, d1.x); 
    CGFloat angle2 = atan2(d2.y, d2.x); 
    [[ImgViewArrowImage layer] setAnchorPoint:CGPointMake(0.0, 0.5)]; 
    [[ImgViewArrowImage layer] setPosition:CGPointMake(159,211)]; 

    ImgViewArrowImage.transform = CGAffineTransformRotate(ImgViewArrowImage.transform, angle1-angle2); 
    } 
} 
+0

當角度1,angle2進入零下可能發生。 – 2012-07-18 12:11:37

+0

你Teodor,這就是我知道,減法去負...但我需要的解決方案.... – 2012-07-18 12:15:09

+0

詹尼斯感謝編輯.. – 2012-07-18 12:16:46

回答

3

我只是刪除從我的代碼2行,現在我的代碼工作,所以最後的代碼是

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event 
{ 
    UITouch *touch = [touches anyObject];   
    NSLog(@"%@",[touch view]); 
    if ([touch view] == ImgViewArrowImage) 
    { 
    CGPoint d1 = [touch locationInView:touch.view]; 
    CGPoint d2 = [touch previousLocationInView:touch.view]; 


    CGFloat angle1 = atan2(d1.y, d1.x); 
    CGFloat angle2 = atan2(d2.y, d2.x); 
    [[ImgViewArrowImage layer] setAnchorPoint:CGPointMake(0.0, 0.5)]; 
    [[ImgViewArrowImage layer] setPosition:CGPointMake(159,211)]; 

    ImgViewArrowImage.transform = CGAffineTransformRotate(ImgViewArrowImage.transform, angle1-angle2); 
    } 
} 
0

根據原來的問題的意見,保持大於0角度:

float _angle = angle1 - angle2; 
if (_angle < 0) _angle += M_PI; // if you are working with radians, otherwise: _angle += 360.f; 

會有另外一個原因:

大家都知道是怎麼atan(...)工作原理:分母爲零時爲未確定,因爲除以是未定義的情況,並且atan(...)的結果在理論上將是無限的,但在float的情況下,您可能會得到MAX_FLOAT值。

+0

沒有它的不工作.... – 2012-07-18 13:00:06

+1

你有沒有試圖檢查兩個原因是什麼? – holex 2012-07-18 13:13:15

+0

好吧,我會檢查... – 2012-07-18 15:34:01

0

使用此代碼:

self.button.layer.anchorPoint = CGPointMake(self.button.layer.anchorPoint.x, self.button.layer.anchorPoint.y*2); 

[UIView beginAnimations:nil context:nil]; 
[UIView setAnimationDuration:0.5f]; 
[self.button setTransform: CGAffineTransformMakeRotation((M_PI/180) * -40.0579987)]; 
[UIView commitAnimations];