Android实现帧动画动态设置播放时间间隔 0 次阅读

前言

前些天在弄一个娱乐小工具App,需要播放gif,但是找了一圈,基本上是使用第三方库的com.felipecsl:gifimageview:2.2.0,和Android帧动画的。

第三方库貌似自定义局限性很大,帧动画的话在xml中把播放时间给写死了,也不好控制。

自带的api只看到getDuration,但是没有setDuration,就离谱。

找了一圈发现是有方法自己去实现setDuration的。

下面直接看怎么实现的:

帧动画实现控制播放时间/速度

帧动画的实现

首先,把帧动画的每一帧图片放到项目的drawable文件夹里。

然后在代码中写成数组待用:

1
2
3
4
5
6
7
8
9
10
11

int[] filesNames = {
R.drawable.sb0,
R.drawable.sb1,
R.drawable.sb2,
...
...
R.drawable.sb42,
R.drawable.sb43
};

利用循环,把每一帧添加到动画中:

1
2
3
4
5
6
7
8
9
10
11

MyAnimationDrawable _animaition = new MyAnimationDrawable();
Drawable frame;
Bitmap bmp;
int n = filesNames.length;
for (int i = 0; i < n; i++) {
bmp = BitmapFactory.decodeResource(getResources(), filesNames[i]);
frame = new BitmapDrawable(getResources(), bmp);
_animaition.addFrame(frame, 100);
}

然后把动画数组到控件里去:

1
2
3

iv.setBackground(_animaition);

以上就把帧动画实现了,下面开始实现帧动画时间/速度的自定义控制。

帧动画时间/速度控制

控制帧动画的时间,函数重写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

//控制帧动画的时间,函数重写
public class MyAnimationDrawable extends AnimationDrawable {

private volatile int duration;//its volatile because another thread will update its value
private int currentFrame;

public MyAnimationDrawable() {
currentFrame = 0;
}

@Override
public void run() {
int n = getNumberOfFrames();
currentFrame++;
if (currentFrame >= n) {
currentFrame = 0;
}
selectDrawable(currentFrame);
scheduleSelf(this, SystemClock.uptimeMillis() + duration);
}

public void setDuration(int duration) {
this.duration = duration;
//we have to do the following or the next frame will be displayed after the old duration
unscheduleSelf(this);
selectDrawable(currentFrame);
scheduleSelf(this, SystemClock.uptimeMillis()+duration);
}
}

然后就可以调用上面实现的函数了:_animaition.setDuration(speed);

speed为自定义时间/速度参数。

最后启动动画:

1
2
3
4
5
6
7
8

//是否仅仅启动一次?
_animaition.setOneShot(false);
if (_animaition.isRunning()) { //是否正在运行?
_animaition.stop(); //停止
}
_animaition.start();//启动

以上就完成了实现Android的帧动画时间控制和速度自定义控制的部署。

附加:音频播放速度控制和播放完毕监控

音频播放速度控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

//设置播放速度
private boolean setPlaySpeed(MediaPlayer mediaPlayer, float speed) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
PlaybackParams params = mediaPlayer.getPlaybackParams();
params.setSpeed(speed);
mediaPlayer.setPlaybackParams(params);
return true;
} catch (Exception e) {
String TAG = "设置播放速度 -------- >>>";
Log.e(TAG, "setPlaySpeed: ", e);
return false;
}
}
return false;
}

音频播放完毕监控

1
2
3
4
5
6
7
8
9

Sound_doing.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// 在播放完毕被回调
// Do something...
};
});

Sound_doing为创建的mediaplayer对象

如:MediaPlayer.create(MainActivity.this, R.raw.sound_success);

结语

(PS:手机上用AIDE码Android,操作起来真的好费眼,还是电脑使用Android Studio方便啊。只不过AIDE方便,随时随地可以码,emmm…)

OK,今天就这样,感谢阅读。

么么哒~~

上一篇 笔记:实现数组排列组合图片合成,做一个NFT生成器!
下一篇 Hexo添加完GitTalk评论系统后报错以及解决办法
感谢您的支持!
微信赞赏码 微信赞赏
支付宝赞赏码 支付宝赞赏