Sunday, July 10, 2011

iPhone - Rotation with a single touch or finger

Code Snippet for rotating a view with single finger.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    touch1=[touch locationInView:self.superview];
    touch2=[touch previousLocationInView:self.superview];

    
    
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    UITouch *touch = [touches anyObject];
    CGPoint currentTouch1=[touch locationInView:self.superview];
    CGPoint currentTouch2=[touch previousLocationInView:self.superview];

    
    CGFloat previousAngle = atan2(touch2.y - touch1.y, touch2.x - touch1.x) * 180 / 3.14;
    CGFloat currentAngle = atan2(currentTouch2.y - currentTouch1.y,currentTouch2.x - currentTouch1.x) * 180 / 3.14;
    
    CGFloat angleToRotate = currentAngle - previousAngle;
    
    CGAffineTransform transform = CGAffineTransformRotate(self.transform, angleToRotate*3.14/180);
    
    self.transform = transform;
    touch1 = currentTouch1;
    touch2 = currentTouch2;
    
    
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    
}

1 comment:

  1. When I use the code, the height and width keep changing. How do I rotate without the frame changing? I just want to change the angle at which the view appears on the screen. Please help.

    ReplyDelete