在自定义视图的Canvas上进行Tween动画

3

我有一个继承了 View 的类,在它的画布上,我使用 onDraw() 方法来绘制所有需要的东西,就像这样:

protected void onDraw(Canvas canvas) {
        synchronized (this) {
                float h = mHeight;
                float w = mWidth;

                canvas.drawColor(Color.WHITE);

                float roadLine= (85.0f/100.0f)*h;

                canvas.drawBitmap(mTop, 0, roadLine-mTop.getHeight(), null);

                //this is what I'd like to animate
                canvas.drawBitmap(mSmoke);

        }
    }

我该如何在这里制作动画(补间动画)?

1个回答

7

你不能在另一个类的onDraw()方法中绘制ImageView

这可能更符合你的需求。

public class SimpleAnimation extends Activity {

Sprite sprite;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    sprite = new Sprite(this);
    setContentView(sprite);
}

class Sprite extends ImageView {

    Bitmap bitmap;
    Paint paint;
    RotateAnimation rotate;
    AlphaAnimation blend;
    ScaleAnimation scale;
    AnimationSet spriteAnimation;

    float centerX;
    float centerY;
    float offsetX;
    float offsetY;

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

        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
        offsetX = bitmap.getWidth() / 2;
        offsetY = bitmap.getHeight() / 2;

        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (spriteAnimation == null) {
            centerX = canvas.getWidth() / 2;
            centerY = canvas.getHeight() / 2;
            createAnimation(canvas);
        }
        canvas.drawBitmap(bitmap, centerX - offsetX, centerY - offsetY, paint);
    }

    private void createAnimation(final Canvas canvas) {

        rotate = new RotateAnimation(0, 360, centerX, centerY);
        rotate.setRepeatMode(Animation.REVERSE);
        rotate.setRepeatCount(Animation.INFINITE);
        scale = new ScaleAnimation(0, 2, 0, 2, centerX, centerY);
        scale.setRepeatMode(Animation.REVERSE);
        scale.setRepeatCount(Animation.INFINITE);
        scale.setInterpolator(new AccelerateDecelerateInterpolator());

        spriteAnimation = new AnimationSet(true);
        spriteAnimation.addAnimation(rotate);
        spriteAnimation.addAnimation(scale);
        spriteAnimation.setDuration(10000L);

        startAnimation(spriteAnimation);

    }
  }
}

'TerrorizedBus' 是我的 'Activity',我在那里使用它获取 'Context'。 - Iulius Curt
好的。但是我该如何为它添加动画效果? - Iulius Curt
@iuliux。我为你扩展了我的答案。希望它有所帮助。如果你需要更多的帮助,请告诉我。 - techi.services
是的,第二个选项就是我想要的。实际上,我已经尝试过这个了,但是我无法把那个 smokeView 放在我的画布上开始动画。 - Iulius Curt
谢谢,我会采纳你的建议,但那只是把它放在屏幕上。我需要对其比例、透明度和位置进行动画处理,持续一秒钟(并且在每个onDraw方法调用时,另一个此动画实例应该从另一个位置开始,并在一秒钟内消失)。 - Iulius Curt
显示剩余7条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接