在图像视图中创建动画

时间:2013-01-18 14:58:09

标签: android image animation imageview

我有一个带默认图像的imageview。现在,当我尝试单击它时,我希望它显示4帧图像的动画。我怎么能做到这一点,我尝试了一种更简单的方法(更多的是一种愚蠢的方法),通过改变图像资源4次,正如预期的那样,图像变化太快,以至于动画图像效果不可见。有什么想法吗?

我试过这种方法:

Gem = (ImageView)v;
    Gem.setImageResource(com.example.gems.R.drawable.bd1);
    Gem.postDelayed(new Runnable() {
        public void run() {
            Gem.setImageResource(com.example.gems.R.drawable.bd2);
            Gem.postDelayed(new Runnable() {
                public void run() {
                    Gem.setImageResource(com.example.gems.R.drawable.bd3);
                    Gem.postDelayed(new Runnable() {
                        public void run() {
                            Gem.setImageResource(com.example.gems.R.drawable.bd4);
                            Gem.postDelayed(new Runnable() {
                                public void run() {
                                }
                            }, 500);
                        }
                    }, 500);
                }
            }, 500);
        }
    }, 500);

它有效,但有没有更好的方法,没有编码太多的线?我有25种图像,每张图像有4帧。

编辑:

我尝试使用xml转换文件:

Java文件:

Resources res = this.getResources();
    Gem = (ImageView)v;
    TransitionDrawable transition;

    transition = (TransitionDrawable)
            res.getDrawable(R.drawable.blue_diamond_animation);
    Gem.setImageDrawable(transition);
    transition.startTransition(3000);

xml文件:

 <transition xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/bd1"></item>
  <item android:drawable="@drawable/bd2"></item>
  <item android:drawable="@drawable/bd3"></item>
  <item android:drawable="@drawable/bd4"></item>
  <item android:drawable="@drawable/invi"></item>
 </transition>

这似乎有效,但我不想在过渡中绘制这些图像。我想在转换中更改背景。我尝试将此android:drawable更改为android:drawable但不起作用。

2 个答案:

答案 0 :(得分:1)

事实证明,有一个确切的类:AnimationDrawable

基本上,只需将动画中使用的其他图片添加到AnimationDrawable对象,并指定使用addFrame(Drawable frame, int duration)显示的时长

然后设置ImageView以显示应该开始的任何图片,并将背景设置为您使用AnimationDrawable

创建的setBackgroundDrawable(Animation)

最后,在onClick监听器

中启动动画

编辑:例如

AnimationDrawable ad = new AnimationDrawable();
ad.addFrame(getResources().getDrawable(R.drawable.image1), 100);
ad.addFrame(getResources().getDrawable(R.drawable.image2), 500);
ad.addFrame(getResources().getDrawable(R.drawable.image3), 300);

ImageView iv = (ImageView) findViewById(R.id.img);
iv.setBackgroundDrawable(animation);

然后在你的onClick监听器中,只需调用ad.start

答案 1 :(得分:0)

这取决于你想要完成的任务。你还没有给出足够的信息

viewproperty动画师真的是最容易使用的东西。它也可以使用旧的API使用nineoldandroids jar(google it)

http://developer.android.com/reference/android/view/ViewPropertyAnimator.html

ObjectAnimator和ValueAnimator也可用,类似,实现起来稍微困难

http://developer.android.com/reference/android/animation/ObjectAnimator.html http://developer.android.com/reference/android/animation/ValueAnimator.html

看一下样本包中的APIdemos,有一些主要使用ValueAnimator的例子。 http://developer.android.com/tools/samples/index.html

还有精灵要考虑,但它基本上是一个位图,你可以使用计时器对象编排