Reputation: 1597
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);
}
}
Upvotes: 1
Views: 769
Reputation: 643
Use this code:
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];
Upvotes: 0
Reputation: 1597
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);
}
}
Upvotes: 3
Reputation: 24041
according to the comments of the original question, to keep the angle above 0:
float _angle = angle1 - angle2;
if (_angle < 0) _angle += M_PI; // if you are working with radians, otherwise: _angle += 360.f;
there would be another reason:
we all knows how the atan(...)
works: it is undetermined when the denominator is zero because dividing by zero is a not defined case, and the result of the atan(...)
will be unlimited theoretically, but in the case of the float
you might get the MAX_FLOAT
value.
Upvotes: 0