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

相关推荐
AsiaLYF8 分钟前
kotlin中MutableStateFlow和MutableSharedFlow的区别是什么?
android·开发语言·kotlin
2501_9160088921 分钟前
iOS 发布全流程详解,从开发到上架的流程与跨平台使用 开心上架 发布实战
android·macos·ios·小程序·uni-app·cocoa·iphone
4Forsee30 分钟前
【Android】浅析 Android 的 IPC 跨进程通信机制
android·java
叶羽西1 小时前
如何区分Android、Android Automotive、Android Auto
android
用户2018792831671 小时前
用 “奶茶店订单系统” 讲懂 MVI 架构
android
LiuYaoheng1 小时前
【Android】布局优化:include、merge、ViewStub的使用及注意事项
android·java
Kapaseker2 小时前
Kotlin Flow 的 emit 和 tryEmit 有什么区别
android·kotlin
好好学习啊天天向上3 小时前
Android Studio 撕开安卓手机投屏
android·智能手机·android studio
Android-Flutter3 小时前
android - JPG图片转换HDR图片,heic格式
android
诸神黄昏EX11 小时前
Android Build系列专题【篇四:编译相关语法】
android