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

相关推荐
xingxiliang2 小时前
深入浅出 Android CTS 视频测试:从环境搭建、用例设计到底层通信原理
android·音视频
我命由我123452 小时前
Android 开发问题:为 PDFView 设置一个带有黑色边框的背景 drawable,但边框没有生效
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
雨白4 小时前
深入理解 Kotlin 协程 (八):拾遗补阙,探秘官方框架的调度细节与取消闭环
android·kotlin
海天鹰6 小时前
PHP上传文件
android·开发语言·php
2501_915918417 小时前
详解iOS App上架至App Store的全流程步骤与注意事项
android·macos·ios·小程序·uni-app·cocoa·iphone
码农coding8 小时前
android12 SystemUI之StatusBar(二)
android
Lesile10 小时前
Interview#1 历史演进:MVC · MVP · MVVM · MVI架构详解
android·android jetpack
杉氧11 小时前
Flutter 像素级还原实战:用 CustomPaint 与 Bezier 曲线手绘精致图针
android·前端·flutter
我命由我1234513 小时前
Android 在构建过程中,发现有两个依赖库都包含了相同路径的资源文件
android·java·开发语言·java-ee·kotlin·android-studio·android runtime
Coffeeee14 小时前
谷歌的一个优化建议,让我重新学了一遍Android里面如何正确处理位图
android·google·kotlin