首页 > 解决方案 > 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[],但动画仍然播放缓慢。

在此处输入图像描述

标签: javaandroidandroid-studio

解决方案


在尝试优化我的代码并没有看到重大改进之后,我现在最好的猜测是动画受到手机显示刷新率(60 赫兹)的限制。虽然我很困惑为什么 android 支持以更小的时间间隔显示帧的方法。


推荐阅读