浅谈Android动画(二) 逐帧动画

逐帧动画

他的原理是将一张张单个的图片连续播放,类似gif效果。

逐帧动画比较建议在xml中实现
在main>res>drawable 目录下面创建 帧动画名字.xml
我这里是 frame_anim.xml

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false"
>
<!-- animation-list 帧动画 -->
<!-- android:oneshot的值为 false代表播放多次,true代表只播放一次 -->
<!-- duration代表每张图片的播放时间 ,定义一个持续时间为50毫秒的动画帧 -->
<item android:drawable="@drawable/ic_fingerprint_0" android:duration="100"/>
<item android:drawable="@drawable/ic_fingerprint_1" android:duration="100"/>
<item android:drawable="@drawable/ic_fingerprint_2" android:duration="100"/>
<item android:drawable="@drawable/ic_fingerprint_3" android:duration="100"/>
<item android:drawable="@drawable/ic_fingerprint_4" android:duration="100"/>
<item android:drawable="@drawable/ic_fingerprint_5" android:duration="100"/>
<item android:drawable="@drawable/ic_fingerprint_6" android:duration="100"/>

</animation-list>

在对应的Java文件中 使用xml定义的动画
AnimationActivity.java

public class AnimationActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView imageView;
private AnimationDrawable animationDrawable;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_animation);
imageView = (ImageView) findViewById(R.id.imageView);
findViewById(R.id.start).setOnClickListener(this);
findViewById(R.id.stop).setOnClickListener(this);
//通过XML添加帧动画
setFrameAnim();
//通过代码添加帧动画
//setFrameAnimation();
}

/**
* 通过XML添加帧动画
*/
private void setFrameAnim() {
// 把动画资源设置为imageView的背景,也可直接在XML里面设置
imageView.setBackgroundResource(R.drawable.frame_anim);
animationDrawable = (AnimationDrawable) imageView.getdrawable();
animationDrawable.start();//开始动画

/**
* 通过代码添加帧动画
*/
private void setFrameAnimation() {
animationDrawable = new AnimationDrawable();
animationDrawable.addFrame(getResources().getDrawable(R.drawable.img_01), 50);
animationDrawable.addFrame(getResources().getDrawable(R.drawable.img_02), 50);
//设置为循环播放
animationDrawable.setOneShot(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
imageView.setBackground(animationDrawable);
}

}

@Override
public void onClick(View view) {

switch (view.getId()) {
case R.id.start:
if (animationDrawable != null && !animationDrawable.isRunning()) {
animationDrawable.start();
}
break;

case R.id.stop:
if (animationDrawable != null && animationDrawable.isRunning()) {
animationDrawable.stop();
}
break;

default:
break;
}
}
}

activity_animation.xml 布局文件只有两个按钮,用来开启动画播放和停止动画播放,这里就不给出了。
建议:选择图片尽量不要选择太大的图片,如果图片太大会造成OOM内存溢出的错误,需要用Bitmap的压缩机制,可以去了解一下Bitmap的压缩机制。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值