2011-10-22 9 views
1

ドラッグされた距離とドラッグされた距離に基づいて加速しようとするUIImageViewがあります。加速すると、touchesEnded:が呼び出されたときに、imageViewがドラッグされた方向にさらにスライドします。どのくらいの速度で滑らなければならないかは、それがドラッグされた距離と速度に依存します。touchesで加速する要素:touchesEnded:

この時点で、イメージビューをドラッグしてドラッグした距離+どのくらいの時間がかかります。これに基づいて、私は速度と方向ベクトルを計算することができます。

しかし、私はtouchesEnded:によって画像ビューで実行されたスライドに苦労しています。

私の質問は:私がしようとしている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が加速します(速度の計算方法に基づいて)。

このような問題に苦労している人なら誰でも役に立つと思います。