安卓动画系列之一,妙用Interpolator 快速实现弹球效果

一直很想写个动画系列,把自己学过的东西好好总结一下,无奈最近都在看源码忙的焦头烂额.现在先写个开篇,以后继续补充动画相关的文章.作为引起兴趣, 这里弹球效果作为一个小例子,顺便讲讲Animation动画中应该利用Interpolator来锦上添花.


这是个很简单的例子,但复杂的东西不都由诸多看似简单的元素组合而成的么.

网上搜索已经有很多关于Interpolator的介绍文章, 这里借用一大神的文章作为介绍http://blog.csdn.net/jason0539/article/details/16370405

Interpolator的引用主要是两种方式,一种是在XML里面直接声明,第二种是在代码里去设置,如果觉得系统提供的Interpolator不够用,还可以自定义参数.

弹球效果,用实现了Interpolator接口的BounceInterpolator来完成.下面直接上例子:

准备动画文件 anim1.xml



    
    
    
    

上面代码中,android:interpolator="@android:anim/bounce_interpolator" 就是引用了系统的BounceInterpolator, 效果是当动画结束的时候会弹起.为了方便看到效果将时间设为2000ms,

MainActivity中main.xml布局文件:


    
    
    
    

最后在MainActivity的onCreate()方法里,加入下面代码:

img = (ImageView)findViewById(R.id.img_main);
      
      Animation anim = AnimationUtils.loadAnimation(MainActivity.this, R.anim.anim1);
      anim.setAnimationListener(new AnimationListener() {
		@Override
		public void onAnimationStart(Animation animation) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onAnimationRepeat(Animation animation) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onAnimationEnd(Animation animation) {
			// TODO Auto-generated method stub
			img.clearAnimation();
			Animation anim = AnimationUtils.loadAnimation(MainActivity.this, R.anim.anim1);
		    anim.setInterpolator(new BounceInterpolator());
		    img.setAnimation(anim);
		}
	});
      
    img.setAnimation(anim);

这样就大功告成,代码很简单,所以没有写注释了,只要在项目中添加代码就能看到效果.因为设置了AnimationListener,在第一次动画结束的时候清空并且再次设置一次动画,同时代码中还设置了BounceInterpolator(这也就是第二种设置Interolator的方法), 所以运行会看到图片有两次弹起效果.

例子简单,但只要善于组合利用,也会有妙笔生花之效呢.其他子类Interpolator,大家即可用类似的方法去调试组合不同的动画以达到更好的效果.

你可能感兴趣的:(安卓开发)