如何在iphone中旋转速度表中的图像

如何在iphone中旋转速度表中的图像,iphone,objective-c,ios,uiimage,cgaffinetransform,Iphone,Objective C,Ios,Uiimage,Cgaffinetransform,以下是触摸时旋转箭头(uiimage)事件的代码。在这里,我减去了之前和当前两次触摸的位置,但问题是箭头(uiimage)有时会朝着触摸的相反方向移动 - (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { UITouch *touch = [touches anyObject]; NSLog(@"%@",[touch view]); if ([touch view] ==

以下是触摸时旋转箭头(uiimage)事件的代码。在这里,我减去了之前和当前两次触摸的位置,但问题是箭头(uiimage)有时会朝着触摸的相反方向移动

- (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以上

float _angle = angle1 - angle2;
if (_angle < 0) _angle += M_PI; // if you are working with radians, otherwise: _angle += 360.f;
float_angle=angle1-angle2;
如果(_角度<0)_角度+=M_PI;//如果使用弧度,则为:_angle+=360.f;
还有另一个原因:


我们都知道
atan(…)
是如何工作的:分母为零时是不确定的,因为除以零是一种未定义的情况,而
atan(…)
的结果在理论上是无限的,但是在
float
的情况下,您可能会得到
MAX\u float
值。

我只是从代码中删除了两行代码,现在我的代码正在工作,所以最后的代码是

- (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);
  } 
}
使用此代码:

 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];

当angle1-angle2降到零下时可能会发生。是的,我知道减法是负数…但我需要解决这个问题…只是一个想法,因为我以前也遇到过同样的问题,它是由第二个原因引起的。。。我只是看到你没有检查你在
atan(…)
函数中使用的参数。我认为问题在于角度是参照主屏幕坐标测量的,因为角度差出错了……这可能就是问题所在。