44

アニメーターをパスにアタッチすることは可能ですか?

キャンバスにアニメーションの線を描く他の方法はありますか?

投稿する前にこれを検索しましたが、何も見つかりませんでした。他の 2 つの投稿Draw a path as animation on Canvas in AndroidHow to draw a path on an Android Canvas with animationには、うまくいかない回避策があります。

コードを onDraw メソッド内に投稿して、必要なものを正確に指定します。

paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(2);
    paint.setColor(Color.BLACK);

    Path path = new Path();
    path.moveTo(10, 50);   // THIS TRANSFORMATIONS TO BE ANIMATED!!!!!!!!
    path.lineTo(40, 50);
    path.moveTo(40, 50);
    path.lineTo(50, 40);
    // and so on...

    canvas.drawPath(path, paint);
4

3 に答える 3

53

キャンバスを時間で変換できます。つまり、次のようになります。

class MyView extends View {

    int framesPerSecond = 60;
    long animationDuration = 10000; // 10 seconds

    Matrix matrix = new Matrix(); // transformation matrix

    Path path = new Path();       // your path
    Paint paint = new Paint();    // your paint

    long startTime;

    public MyView(Context context) {
        super(context);

        // start the animation:
        this.startTime = System.currentTimeMillis();
        this.postInvalidate(); 
    }

    @Override
    protected void onDraw(Canvas canvas) {

        long elapsedTime = System.currentTimeMillis() - startTime;

        matrix.postRotate(30 * elapsedTime/1000);        // rotate 30° every second
        matrix.postTranslate(100 * elapsedTime/1000, 0); // move 100 pixels to the right
        // other transformations...

        canvas.concat(matrix);        // call this before drawing on the canvas!!

        canvas.drawPath(path, paint); // draw on canvas

        if(elapsedTime < animationDuration)
            this.postInvalidateDelayed( 1000 / framesPerSecond);
    }

}
于 2013-09-04T15:31:41.833 に答える
3

パスの を作成し、PathMeasureその長さを決定できます。

private PathMeasure pathMeasure; // field

// After you've created your path
pathMeasure = new PathMeasure(path, false); 
pathLength = pathMeasure.getLength();

次に、たとえば ValueAnimator の更新リスナー内で getPosTan() を使用して、パス上の特定のポイントを取得できます。

final float[] position = new float[2]; // field

// Inside your animation's update method, where dt is your 0..1 animated fraction
final float distance = dt * pathLength;
pathMeasure.getPosTan(distance, position, null);

// If using onDraw you'll need to tell the view to redraw using the new position
invalidate(); 

その後、onDraw (または何でも) で位置を利用できます。

canvas.drawCircle(position[0], position[1], radius, paint);

このアプローチの利点は、単純で、分厚い計算を必要とせず、すべての API で機能することです。

API 21 以降を使用している場合は、ValueAnimator を使用し、Path を渡してその位置を使用できます。これはより簡単です。 例 SO の質問

于 2016-03-22T22:58:42.813 に答える