【问题标题】:Accelerating elements with touchesBegan: and touchesEnded:使用 touchesBegan: 和 touchesEnded: 加速元素
【发布时间】:2011-10-22 13:31:35
【问题描述】:

我有一个 UIImageView,我尝试根据它被拖动的距离和拖动速度来加速它。通过加速我的意思是当 touchesEnded: 被调用时,imageView 应该在它被拖动的方向上滑动得更远。它应该滑动多远和多快取决于它被拖动的距离和速度。

此时我可以拖动 imageview 并获得拖动的距离 + 花费了多长时间。基于此,我可以计算出速度和方向向量。

但我正在努力处理 touchesEnded: 在 imageview 上执行的幻灯片。

我的问题是:是否有任何常见或聪明的方法可以在我尝试做的 UIImageView 上执行这种“滑动”效果?

我很乐意接受任何可能有帮助的解决方案或提示。

谢谢。

【问题讨论】:

    标签: ios ipad uitouch touchesbegan


    【解决方案1】:

    这个问题的解决方案比我预想的要简单得多。以下是我想出的(这是简单的版本,没有所有花哨的代码):

    @interface myViewController {
        CGPoint _velocity;
        CGFloat _damping;
        UIImageView *_myImageView;
    }
    
    - (void)viewDidLoad {
        _velocity = CGPointZero; // x = 0, y = 0
    
       // Accelerate _myImageView 
       NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:0.02f // Update frequency 
                                                   target:self 
                                                 selector:@selector(slideImageView) 
                                                 userInfo:nil 
                                                  repeats:YES];
    }
    
    @implementation myViewController
    
    - (void)slideImageView {
        // No need to move _myImageView when _velocity = 0
        if (_velocity.x > 0 && _velocity.y > 0)
            CGPoint position; // The next position
            position = _myImageView.center;
    
            position.x += _velocity.x / 30;
            position.y += _velocity.y / 30;
    
            // Damp _velocity with damping factor
            _velocity.x *= _damping;
            _velocity.y *= _damping;
    
            // Bounce on edges
            if (position.x < X_AXIS_MIN_VALUE || position.x > X_AXIS_MAX_VALUE)
                _velocity.x = -_velocity.x;
    
            if (position.y < Y_AXIS_MIN_VALUE || position.y > Y_AXIS_MAX_VALUE)
                _velocity.y = -_velocity.y;
    
            // Move 
            _myImageView.center = position;
        }
    }
    
    // Move been around by implementing touchesBegan: and touchesMoved:
    // There are a million tutorials on how to do this.
    
    - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
        // Do whatever you need to do and calculate x- and y-axis velocity,
        // maybe based on the distance between the last 5 points / time.
        CGPoint mySpeed;
        mySpeed.x = //the new x speed;
        mySpeed.y = //the new y speed
        _velocity = mySpeed;
    }
    
    @end
    

    上面的代码(+ 缺少的实现)允许您在屏幕上拖动 UIImageView。当您松开手指时,ImageView 将继续在屏幕上滑动,如果它们被击中,则会在边缘弹跳。您移动手指的速度越快,ImageView 将加速得越快(嗯,取决于您计算速度的方式)。

    我希望任何遇到过此类问题的人都会发现它很有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多