【问题标题】:animationDrawable only displays last frameanimationDrawable 只显示最后一帧
【发布时间】:2019-03-02 10:39:39
【问题描述】:

我正在尝试使用多个 png 图像创建动画。这是我的代码:

AnimationDrawable animation = new AnimationDrawable();

for (int i = 0; i < translate_text.length(); i++)
{
    byte[] byteArray = Base64.getDecoder().decode(client._fromServer.elementAt(i));
    Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    ImageView image = (ImageView) findViewById(R.id.sign);
    image.setImageBitmap(Bitmap.createScaledBitmap(bmp, image.getWidth(), image.getHeight(), false));
    animation.addFrame(image.getDrawable(), 1000);
}

animation.setOneShot(true);
animation.start();

但这只显示最后一帧...有什么想法吗?

编辑:可能应该早点这样做,但这里是:

translate_text 是一个字符串。它代表图像序列。例如,如果字符串是“bob”,那么应该有 3 个图像:字母 B、字母 O 和字母 B。

client._fromServer 是一个字符串向量。每个字符串都是以 base64 编码的图像本身。这就是为什么 client._fromServer.elementsAt(i) 是一个需要解码并转换为 byteArray 的字符串。

【问题讨论】:

  • 调试代码时,translate_text的值是多少?您确定每次循环迭代都会得到不同的图像吗?这是什么client._fromServer.elementAt(i)(真的很奇怪)?
  • translate_text 是一个字符串,其中每个字符代表一个图像(例如,如果字符串是“bob”,那么我将有 3 个图像:字母 B、字母 O 和字母 B)。 client._fromServer.elementAt(i) 是图像的字符串表示形式(以 base64 编码)。是的,我真的很确定它在每次循环迭代时都会得到不同的图像@florian

标签: java animationdrawable


【解决方案1】:

我认为这是因为您从同一个 ImageView 获得了 Drawable
当您执行image.setImageBitmap() 时,它会更新 ImageView 中 Drawable 的引用,并且 AnimationDrawable 也会受到影响。
您应该为每个 addFrame 调用使用不同的 Drawable 实例。

类似的东西:

AnimationDrawable animation = new AnimationDrawable();
ImageView image = (ImageView) findViewById(R.id.sign);

for (int i = 0; i < translate_text.length(); i++)
{
    byte[] byteArray = Base64.getDecoder().decode(client._fromServer.elementAt(i));
    Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    final Bitmap scaledBitmap = Bitmap.createScaledBitmap(bmp, image.getWidth(), image.getHeight(), false);
    Drawable drawable = new BitmapDrawable(getResources(), scaledBitmap);
    animation.addFrame(drawable, 1000);
}

animation.setOneShot(true);
animation.start();

【讨论】:

  • 我编辑了我的答案,使其更清晰。在您发布的屏幕截图中,您仍在使用相同的图像实例,因此是可绘制的。如果仍然不清楚为什么会发生这种情况,请随时询问更多详细信息。
  • 哦,我想我明白了,谢谢!我试过你的代码,我认为它可以工作,但它没有显示在屏幕上,它应该放在原始 ImageView 的位置吗?还是我应该做些什么来设置它的坐标或其他什么?
  • 在for循环之后,image.setImageDrawable(animation);.
猜你喜欢
  • 2021-07-18
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-29
  • 2016-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多