关于TimeInterpolator的冷门用法

关键词:插值器、TimeInterpolator、帧率、动画

1、前情提要

在一款屏保应用的开发中,需要防止屏幕因长时间显示同一颜色而老化,需要让TextView和静态的图片适当移动、放大,但是不能让用户察觉UI的元素在动,需要控制在30min完成一轮循环。

2、动画实现

这里简单创建一个实现30min无限左右平移100px的动画:

java 复制代码
private final static int DURATION_30_MIN_MILL = 30 * 60 * 1000;
private void startAnimator() {
    ObjectAnimator animator = ObjectAnimator.ofFloat(findViewById(R.id.hello), "translationX", 100);
    animator.setInterpolator(new LinearInterpolator());
    animator.setDuration(DURATION_30_MIN_MILL);
    animator.setRepeatCount(ObjectAnimator.INFINITE);
    animator.setRepeatMode(ObjectAnimator.REVERSE);
    animator.start();
}

3、LinearInterpolator问题

如果这样实现,看起来View几乎没有动,但是应用还是以满帧率去做动画的,CPU占用十分惊人:

前三个关联进程占用加起来跑了满1个多CPU核心

4、TimeInterpolator使用

java 复制代码
private final static int FRAME_COUNT = 360; // -> 360frame / 3600s = 0.1fps
private final static int DURATION_30_MIN_MILL = 30 * 60 * 1000;
private final TimeInterpolator mTimeInterpolator = input -> (int) (input * FRAME_COUNT) / (FRAME_COUNT * 1.0f);

private void startAnimator() {
    ObjectAnimator animator = ObjectAnimator.ofFloat(findViewById(R.id.hello), "translationX", 100);
    animator.setInterpolator(mTimeInterpolator);
    animator.setDuration(DURATION_30_MIN_MILL);
    animator.setRepeatCount(ObjectAnimator.INFINITE);
    animator.setRepeatMode(ObjectAnimator.REVERSE);
    animator.start();
}

使用TimeInterpolator后,可以计算出动画帧率只有0.1fps,CPU使用率也降低到个位数:

总结

水文一篇,该使用场景比较少,如果有长时间移动和帧速率控制的需求,使用TimeInterpolator可能对你有所帮助。

相关推荐
auxor3 小时前
Android 开机动画音频播放优化方案
android
whysqwhw3 小时前
安卓实现屏幕共享
android
深盾科技3 小时前
Kotlin Data Classes 快速上手
android·开发语言·kotlin
一条上岸小咸鱼4 小时前
Kotlin 基本数据类型(五):Array
android·前端·kotlin
whysqwhw4 小时前
Room&Paging
android
whysqwhw4 小时前
RecyclerView超长列表优化
android
Tiger_Hu4 小时前
Android系统日历探索
android
whysqwhw4 小时前
RecyclerView卡顿
android
whysqwhw4 小时前
RecyclerView 与 ListView 在性能优化方面
android
檀越剑指大厂7 小时前
容器化 Android 开发效率:cpolar 内网穿透服务优化远程协作流程
android