关于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可能对你有所帮助。

相关推荐
三少爷的鞋6 小时前
为什么成熟 Android 项目几乎看不到 IdleHandler?
android
kururunga7 小时前
Android知识点回顾之蓝牙协议
android·蓝牙·车载开发
StarsGreen8 小时前
aosp中的SELinux 策略配置和编译流程
android
方白羽11 小时前
Android 开发中常见的编译加速方案
android·app·gradle
StarsGreen14 小时前
Android VINTF 中 Device Manifest 与 Framework Manifest 详解
android
Name_NaN_None16 小时前
安卓手机远程控制电脑方法(Android/Windows) —— 「小白教程」
android·windows·智能手机·电脑·笔记本
恋猫de小郭16 小时前
Flutter Perfetto:Dart Heap Sampling 终于要接入 Android 原生内存分析了
android·前端·flutter
敢敢のwings1 天前
GR00T 2:当机器人学会先想象未来,再决定怎么动
android·机器人
传奇开心果编程1 天前
【Jetpack Compose娓娓道来】第55课:传感器与设备姿态——把物理世界的数据接进Compose
android·kotlin·移动开发·传感器·jetpack compose·ui框架·声明式ui
传奇开心果编程1 天前
【Jetpack Compose娓娓道来】第52课:蓝牙与位置权限——把“附近”和“在哪”安全地接进Compose
android·kotlin·移动开发·蓝牙·jetpack compose·声明式ui·位置权限