在imageviews中创建动画



我有一个默认图像的imageview。当我点击它时,我想让它动画显示4帧图像。我怎么能做到这一点,我尝试了一个更简单的方法(更愚蠢的方法)通过改变imagerresource 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:drawableandroid:drawable,但它不工作。

结果是有一个确切的类:AnimationDrawable

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

指定它们应该显示多长时间

然后将ImageView设置为显示它应该开始的任何图像,并将背景设置为您刚刚使用setBackgroundDrawable(Animation)创建的AnimationDrawable

最后,在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

这取决于你想要完成什么。你没有提供足够的信息

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

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

ObjectAnimator和ValueAnimator也有类似的,但实现起来稍微困难一些

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

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

也需要考虑精灵,但它基本上是位图,你可以使用计时器对象来编排

最新更新