以下是用于在触摸事件上旋转箭头(uiimage)的代码。在这个i中减去前面和当前两个触摸的位置,但问题是箭头(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 :(得分: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);
}
}
答案 1 :(得分: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
值。
答案 2 :(得分: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];