我已经在这里阅读了一些相关示例,但无法使其发挥作用。 我有一些名为 Wheel 的 UIView ,我想在其中触摸和拖动时旋转。 它应该像真正的轮子一样工作,所以如果我触摸某个点,它不会旋转到该点,只有当我拖动手指时,我才会旋转。
我尝试过这个,但是我所做的每一个小 Action 都会得到一个完整的旋转。我想将天使添加到 View 中,而不是旋转到新天使..
- (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 );
}
最佳答案
这应该可以解决问题。请注意我如何将第一个接触点存储在 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;
}
关于ios - 转动轮子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29233033/