【问题标题】:How to place AnimationDrawable on a SurfaceView canvas如何将 AnimationDrawable 放置在 SurfaceView 画布上
【发布时间】:2011-08-05 18:25:53
【问题描述】:

游戏开发新手,我在将 AnimationDrawable 放置到 SurfaceView 画布上时遇到问题。这是一个简单游戏的一部分,用户触摸屏幕,一个动画 gif 被放置在那个看起来像爆炸的位置。我可以使用下面显示的代码通过位图来完成此操作,但是将其转换为 AnimationDrawable 是我卡住的地方。我可以从 ImageView 创建 AnimationDrawable,但我也找不到将 ImageView 放到画布上的方法...

我是否以错误的方式处理这件事?有没有更简单的方法让动画 gif 显示在 SurfaceView 画布上的 x,y 坐标处?

Bitmap explodeBmp = BitmapFactory.decodeResource(getResources(), R.drawable.explode4);
canvas.drawBitmap(explodeBmp, coords.getX()-(explodeBmp.getWidth()/2), coords.getY()-(explodeBmp.getHeight()/2), paint);

如果我尝试将 Bitmap 转换为 AnimationDrawable 并启动它,则会引发 ClassCastException:

AnimationDrawable explosionAnimation = (AnimationDrawable) ((Drawable) new BitmapDrawable(explodeBmp));
explosionAnimation.start();

【问题讨论】:

  • 任何人至少有一个提示?评论?引领正确的方向?有游戏开发者吗?

标签: android canvas bitmap surfaceview


【解决方案1】:

经过不断的挖掘,我找到了答案……似乎我喜欢在这里回答我自己的问题。

刚刚找到 Movie 类。我可以使用 InputStream 将动画 gif 加载到其中,然后在我的 onDraw() 中一点一点地播放电影,因为 Movie 类支持 draw() 方法,我可以在其中提供我的画布和 x,y 坐标。

下面是代码片段:

InputStream is = context.getResources().openRawResource(R.drawable.dotz_explosion);
Movie explodeGif = Movie.decodeStream(is);

...

@Override
protected void onDraw(Canvas canvas) {
    ...
      GraphicObject explosion = (GraphicObject)ex.next();

      long now = android.os.SystemClock.uptimeMillis();
      if (explosion.getMovieStart() == 0) { // first time
         explosion.setMovieStart(now);
      }

      int relTime = (int)((now - explosion.getMovieStart()) % explodeGif.duration());
      if ((now - explosion.getMovieStart()) >= explodeGif.duration()) {
         removeArrayExplosions.add(removeIndex);
         explosion.setMovieStart(0);
      } else {
         explodeGif.setTime(relTime);
         explodeGif.draw(canvas, explosion.getX()-(explodeGif.width()/2), explosion.getY()-(explodeGif.height()/2));
      }
    }
   ...
}

【讨论】:

  • 不推荐使用 gif 图像:非常不鼓励。您应该使用 XML 中定义的动画列表。使用电影会非常昂贵。对于现在在谷歌上搜索的人:stackoverflow.com/questions/6531246/…
  • @RichieHH 在内存使用方面非常昂贵?我有几个旧机器人,我尝试过我的应用程序,但看不到任何性能问题。我已经同时播放了几十部电影,没有任何问题。
  • 相反,根据我的经验,使用动画列表很昂贵。列表中的每一块都会生成一个隔离位图,这会消耗大量内存。
猜你喜欢
  • 2013-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多