java - Android Studio 中的动画太慢了
问题描述
我想在我的 Android 应用程序中显示最多包含 127 个 png 文件的动画。但是,我不能让他们玩得像我想的那样快。正如您在下面看到的,我创建了一个AnimationDrawable
对象并将 png 文件作为框架添加到它。我打电话animation.addFrame(frame, 1)
所以总动画应该播放 127 毫秒(127 帧 x 1 毫秒),但在我的手机上播放需要超过一秒钟。通过分析我的代码,我看到byte[]
了大部分内存使用量的贡献,我尝试通过进一步调整图像大小来解决这个问题。但是,动画的速度仍然远未接近 127 毫秒。最好的行动方案是什么?
void createAnimation(AnimationDrawable animation, int endFrameIdx){
for (int i = 0; i < endFrameIdx; i++) {
String name = idArray[i]; // idArray contains name of png files
int id = getResources().getIdentifier(name, "drawable", getPackageName());
Drawable d = ContextCompat.getDrawable(this, id);
Drawable compressD = resize(d);
animation.addFrame(compressD, 1);} // 1 ms per frame
}
}
private Drawable resize(Drawable image) {
Bitmap b = ((BitmapDrawable)image).getBitmap();
Bitmap bitmapResized = Bitmap.createScaledBitmap(b, 90, 161, true);
return new BitmapDrawable(getResources(), bitmapResized);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageanim = findViewById(R.id.imageanim);
AnimationDrawable animation = new AnimationDrawable();
int stopFrameIdx = 270; // maximum # of frames to add to animation
createAnimation(animation, stopFrameIdx);
imageanim.setImageDrawable(animation);
animation.start();
配置文件代码。调整 png 文件的大小会减少 消耗的内存byte[]
,但动画仍然播放缓慢。
解决方案
在尝试优化我的代码并没有看到重大改进之后,我现在最好的猜测是动画受到手机显示刷新率(60 赫兹)的限制。虽然我很困惑为什么 android 支持以更小的时间间隔显示帧的方法。
推荐阅读
- delta-lake - Delta Lake 从模式创建表
- google-app-engine - Google App Engine Node 应用程序:防止缩减为 0 个实例
- flutter - 为 GridView 中的每个其他项目添加价值
- angular - 如何以编程方式更新 Angular ng2-semantic 的 sui-select 元素的选定值
- c - 如何更改 char* 全局?
- javascript - Math.Random() 在选择数组项时选择更多
- ios - 新的 iOS 13 模态演示:演示控制器不会向下移动
- javascript - 使用 Gatsby 和模板进行分页
- javascript - 带有动态锚链接的 OnServerClick 未触发
- java - 无法将 java.lang.String 类型的对象转换为类型(Firebase、RecyclerView)