ios - 转动轮子?

标签 ios objective-c

我已经在这里阅读了一些相关示例,但无法使其发挥作用。 我有一些名为 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: 中。这使我可以从拖动时获得的每个触摸点中减去第一个触摸点,从而为我提供需要旋转的真实角度。

编辑

我做了一些调整,现在即使在多次触摸之后它也变得平滑和规则。

演示

enter image description here

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/

相关文章:

ios - 尝试在异常 : _descendantWillPresentViewController 中呈现模态结果

ios - 在没有 use_frameworks 的情况下使用 cocoapods!在 swift

iphone - 如何根据 objective-c 中的内容设置UITextView的高度

ios - 重构大型方法以在 UIViewController 中创建自定义 UIView

ios - 我的应用被 Apple 拒绝了

objective-c - 在 iOS 中获得 root 访问权限并启动 Daemon

ios - Flutter 我想把界面设计成这样,大家能帮帮我吗?我正在设计一个关于页面,但我遇到了问题

ios - supportedInterfaceOrientations 在除 6+ 以外的所有 iPhone 上调用

ios - 使用自定义按钮登录 Facebook

iphone - 如何禁用 iphone 中的多个按钮?