使用touchesBegan:和touchesEnded:加速元素



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

在这一点上,我可以拖动imageview并得到它被拖动的距离+它花了多长时间。在此基础上,我可以计算速度和方向矢量。

但是我正在与touchesEnded:在imageview上执行的幻灯片作斗争。

我的问题是:是否有任何共同或聪明的方法来执行这种"滑动"效果在UIImageView,我试图做的?

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

谢谢。

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

@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加速的速度就越快(好吧,这取决于你如何计算速度)。

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