1

ドラッグされた距離とドラッグされた速さに基づいて加速しようとする UIImageView があります。加速するとは、touchesEnded: が呼び出されたときに、imageView がドラッグされた方向にさらにスライドすることを意味します。スライドする距離と速度は、ドラッグした距離と速度によって異なります。

この時点で、イメージビューをドラッグして、ドラッグされた距離と所要時間を取得できます。これに基づいて、速度と方向ベクトルを計算できます。

しかし、touchesEnded: によって imageview で実行されるスライドに苦労しています。

私の質問は次のとおりです。私がやろうとしている UIImageView でこの「スライド」効果を実行する一般的またはスマートな方法はありますか?

役立つ解決策やヒントを喜んで受け入れます。

ありがとう。

4

1 に答える 1

-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 は加速します (速度の計算方法に基づきます)。

このような問題に苦しんでいる人に役立つことを願っています。

于 2011-10-24T11:07:40.723 に答える