Search code examples
iphoneobjective-ciosuiimagecgaffinetransform

How to rotate image in the speedometer in iphone


Following is a code for rotate the arrow(uiimage) on touch event. in this i subtract the position of the two touches previous and current but problem is that the arrow(uiimage) sometime moves in a opposite direction of the touch.

- (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);
  } 
}

Solution

  • i just remove 2 lines from my code and my code is working now so the final code is

    - (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);
      } 
    }