Android通过动画实现图片重复放大和缩小

来源:互联网 发布:易直帮app软件下载 编辑:程序博客网 时间:2024/06/15 05:35
Android动画有两种,Tween Animation(补间动画)和Frame Animation(帧动画),在API11以上的动画被分为三类Property Animation, View Animation(即补间动画)和Drawable Animation(即帧动画,想放电影一样展示图片)。
下面主要说的是Tween Animation。
Tween Animation是对视图对象中的内容进行一系列简单的图形转换,如移动、缩放、旋转、透明变化等。Animation可以通过代码直接实现,也可以通过xml实现。Tween的XML文件放在工程的res/anim目录中,这个目录中要包好一个根元素,可以是<scale>,<transplate>,<alpha>或者<rotate>,表示缩放、平移、透明和旋转,也可以把这些元素都放在一个动画集<set>中,默认情况下在<set>集合中所有动画指令都是同时发生的,为了让他们顺序发生,可以通过每个元素的startOffset属性设置开启动画时间。下面就是一个实现缩放的XML例子:
<?xml version="1.0" encoding= "UTF-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"    android:shareInterpolator="false" ><scale         android:interpolator="@android:anim/accelerate_decelerate_interpolator"         android:fromXScale="0.3"         android:toXScale="1.0"         android:fromYScale="0.3"         android:toYScale="1.0"         android:pivotX="50%"         android:pivotY="50%"         android:duration="5000"         android:repeatCount="-1"           android:repeatMode="reverse" /></set>
这里解释一下这个XML的含义:这里定义了一个缩放<scale>,它放在了集合<set>中,如果只实现单一的缩放,可以不写set,但一般都写上以便于扩展。<scale>属性分析:
android:interpolator:动画的插入器,用于描述动画的运行情况,常用的有accelerate_decelerate_interpolator(先加速后减速),accelerate_interpolator(加速器)等
android:fromXScale:X轴开始动画缩放的比例
android:toXScale:X轴结束时动画缩放的比例
android:fromYScale:Y轴开始动画缩放的比例
android:toYScale:Y轴结束动画缩放的比例,以上四个属性定义了将图片从0.3的比例大小放大到1.0的比例大小(即原大小)
android:pivotX:固定点X轴坐标
android:pivotY:固定点Y轴坐标
android:duration:动画持续时间,5000表示5000毫秒,即5秒
android:repeatCount:动画重复次数,-1表示无限循环重复

android:repeatMode:重复模式,reverse表示反向进行,在这里先放大,后缩小

动画文件写好后,先写一个布局文件,这样我们就可以在代码中操控这个布局文件实现,在布局文件中添加以下控件:

 <ImageView        android:id="@+id/image_balloon"        android:layout_width="160dp"        android:layout_height="220dp"        android:layout_alignParentBottom ="true"        android:layout_centerHorizontal ="true"        android:layout_gravity="center_horizontal"        android:src="@drawable/balloon" />
然后在这个布局文件对应的activity(注意一定要是布局对应的activity,否则会发生资源找不到的错误)中实现以下代码:

     /**        * 动画        */    Animation mAnimation = null ;               /**       * 显示动画的ImageView       */    ImageView mImageView = null;     ......       mImageView =(ImageView)findViewById(R.id.image_balloon);             mAnimation = AnimationUtils.loadAnimation(this,R.anim. balloonscale);             mImageView.setAnimation(mAnimation );             mAnimation.start();

实现结果如下:



原创粉丝点击