我在这里已经阅读了一些关于此的例子,但无法使其发挥作用。 我有一些名为Wheel的UIView,我想在触摸和拖动时旋转。 它应该像真正的轮子一样工作,所以如果我在某个点触摸它将不会旋转到那个点,只有当我拖动我的手指时,我才会旋转。
我尝试了这个,但是我得到了一个完整的轮换,我做的每一个小动作。我想把天使添加到视图中,而不是转向新天使..
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPoint = [touch locationInView:self];
CGPoint center=wheel.center;
float xLeg = fabs(center.x - touchPoint.x);
float yLeg = fabs(center.y-touchPoint.y);
float angle = atan(xLeg / yLeg);
NSLog(@"%f",angle);
wheel.transform = CGAffineTransformMakeRotation( angleInDegree );
}
答案 0 :(得分:1)
这应该可以解决问题。请注意我如何在touchesBegan:withEvent:
中存储第一个触摸点。这允许我从拖动时获得的每个触摸点中减去第一个触摸点,从而为我提供需要旋转的真实角度。
修改强>
我已经做了一些调整,所以即使经过几次触摸,它现在也很流畅和规律。
<强>演示强>
<强> WheelViewController.m 强>
@interface WheelViewController () {
CGPoint startPoint;
CGFloat startAngle;
CGFloat endAngle;
}
@end
@implementation WheelViewController
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
startPoint = [touch locationInView:self.view];
startAngle = [self angleForTouchPoint:startPoint] - endAngle;
NSLog(@"\r\nStart angle: %f", startAngle);
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPoint = [touch locationInView:self.view];
CGFloat touchAngle = [self angleForTouchPoint:touchPoint];
NSLog(@"Touch angle: %f", touchAngle);
self.wheel.transform = CGAffineTransformMakeRotation(fmodf(touchAngle - startAngle, 2 * M_PI));
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPoint = [touch locationInView:self.view];
endAngle = [self angleForTouchPoint:touchPoint] - startAngle;
NSLog(@"End angle: %f", endAngle);
}
- (CGFloat)angleForTouchPoint:(CGPoint)touchPoint {
CGPoint center = self.wheel.center;
float xLeg = touchPoint.x - center.x;
float yLeg = touchPoint.y - center.y;
float angle = fmodf(atan(yLeg/xLeg), (2 * M_PI));
if (xLeg < 0) {
angle += M_PI;
}
return angle;
}