2011-10-22 60 views
1

我有一个UIImageView,我尝试根据它被拖动的距离以及拖动的速度来加速。通过加速我的意思是,当touchesEnded:被调用时,imageView应该沿着被拖动的方向进一步滑动。滑动的距离和速度取决于距离和拖动的速度。用touchesBegan加速元素:touchesEnd:

在这一点上我能够左右拖动ImageView的和得到的距离就被拖到+它的时候花了多长时间。基于此,我可以计算速度和方向矢量。

但我正在用touchesEnded:在imageview上执行幻灯片。

我的问题是:是否有执行上,我试图做的这个UIImageView的“滑动”效应任何普通或智能的方式?

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

谢谢。

回答

-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加速的速度就越快(当然,根据您计算速度的方式)。

我希望任何与此类问题斗争的人都会发现它很有用。