ios - 使用 touchesBegan 加速元素 : and touchesEnded:

标签 ios ipad uitouch touchesbegan

我有一个 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 的加速度就越大(当然,这取决于您计算速度的方式)。

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

关于ios - 使用 touchesBegan 加速元素 : and touchesEnded:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7859903/

相关文章:

ios - NSDateFormatter dateFromString崩溃

iphone - TabBar 图像插入不传输到 AdHoc 构建

iphone - XCode 4 - 通用应用程序 - 使用选项卡栏 Controller 时 View 不会改变

objective-c - 使用 UIButtons 和 CoreAnimation 创建柔和的随机运动

iphone - 如何识别特定 View 中的触摸

ios - 有人知道 Adob​​e Scan 的 iOS 自定义方案吗?

ios - iOS联系人备份我们需要保存的文件扩展名

iphone - 将 subview 添加到 UITableViewCell 问题

javascript - 如何检测浏览器地址栏是否显示在 iOS 设备上?

ios - 将触摸事件传递给多个选项之一