imageview没有跟踪android的路径

时间:2011-10-20 19:33:01

标签: android animation imageview

我正在使用翻译动画来使imageview跟踪路径。最初我只是让我的imageview翻译通过一组特定的点,但它没有。我的代码在ondraw方法中有:

@Override
    public void onDraw(Canvas canvas) {
         Log.w(this.getClass().getName(),"onDraw of Balls called");
      super.onDraw(canvas);
      mCanvas = canvas;



         canvas.drawLine(0, 240, 160, 0, mPaint);
         canvas.drawLine(160, 0, 320, 240, mPaint);

         mBal = (ImageView)findViewById(R.id.strike);
         TranslateAnimation mTrans = new TranslateAnimation(0, 240, 160, 0);
         mTrans.setDuration(6000);
         mTrans.setFillEnabled(true);
         mTrans.setFillAfter(true);
         mTrans.start();

    }

帮助。

=============================================== ==============

编辑1: -

这是我修改后的代码,但翻译仍然无效.PLz帮助

@Override
    public void onDraw(Canvas canvas) {

      Log.w(this.getClass().getName(),"onDraw of Balls called");

      BallsOnDraw(canvas);

    }

     void BallsOnDraw(Canvas canvas)
     {

            canvas.drawLine(0, 240, 160, 0, mPaint);
            canvas.drawLine(160, 0, 320, 240, mPaint);

            TranslateAnimation mTrans = new TranslateAnimation(0, 320, 0,240);

            mTrans.setDuration(6000);
            SitoliaActivity.mBal.startAnimation(mTrans);


     }

1 个答案:

答案 0 :(得分:1)

您正在使用ImageView和动画混合自定义类。恕我直言,你应该只使用其中一种方法。另外,我没有看到您实际上将TranslationAnimation与ImageView本身连接起来。

因此,一种解决方案是使用TranslateAnimation,但是你需要调用mBal.startAnimation(mTrans)而不是mTrans.start()。

另一个解决方案是使用自定义视图,覆盖onDraw,并自己处理动画:

  • 保存当前时间(System.curentTimeMillis)
  • 使用canvas.drawBitmap(位图,x,y,paint)将Bitmap直接绘制到Canvas;
  • 根据已用时间更新坐标
  • 如果动画仍应运行,请调用postInvalidateDelayed(40);

以下是自定义视图示例:

public class C extends View {

    private static final float FROM_X = 400;
    private static final float FROM_Y = 100;
    private static final float TO_X = 10;
    private static final float TO_Y = 400;
    private static final int DURATION = 2*1000; // 2 seconds

    private Bitmap mImage;
    private long mStart = -1;
    private Paint mPaint = new Paint();

    public C(Context context) {
        super(context);
        mImage = ((BitmapDrawable)context.getResources().getDrawable(R.drawable.icon)).getBitmap();
    }

    @Override
    public void onDraw(Canvas canvas) {
        boolean finished = false;
        if (mStart == -1) {
            // Time to start the animation
            mStart = SystemClock.uptimeMillis();
        }
        int elapsed = (int)(SystemClock.uptimeMillis() - mStart);
        if (elapsed >= DURATION) {
            elapsed = DURATION;
            finished = true;
        }
        float x = FROM_X + (TO_X - FROM_X) * elapsed / DURATION;
        float y = FROM_Y + (TO_Y - FROM_Y) * elapsed / DURATION;
        canvas.drawBitmap(mImage, x, y, mPaint);
        if (!finished) {
            postInvalidateDelayed(10);
        }
    }

}