2013-05-25 56 views
3

我想在Android应用程序中播放动画GIF。将动画GIF作为动画播放仅显示画布背景

我注意到一个WebView中正常工作与此代码:

webview.loadUrl("file:///android_asset/gif.gif"); 

不幸的是,Webview是太内存密集型和我的应用程序经常崩溃。

我已经看到了很多用电影这样一个教程:

public class GIFView extends View { 
    private Movie movie; 
    private long moviestart; 

    public GIFView(Context context) throws IOException { 
     super(context); 
     movie = Movie.decodeStream(getResources().getAssets().open("gif.gif")); 
    } 

    public GIFView(Context context, AttributeSet attrs) throws IOException { 
     super(context, attrs); 
     movie = Movie.decodeStream(getResources().getAssets().open("gif.gif")); 
    } 

    public GIFView(Context context, AttributeSet attrs, int defStyle) 
      throws IOException { 
     super(context, attrs, defStyle); 
     movie = Movie.decodeStream(getResources().getAssets().open("gif.gif")); 
    } 

    private long _start_time; 

    @Override 
    protected void onDraw(Canvas canvas) { 
     canvas.drawColor(Color.RED); 
     super.onDraw(canvas); 

     long _current_time = android.os.SystemClock.uptimeMillis(); 
     if (0 == _start_time) { 
      _start_time = _current_time; 
     } 
     if (null != movie) { 
      final int _relatif_time = (int) ((_current_time - _start_time) % movie 
        .duration()); 
      movie.setTime(_relatif_time); 
      Log.i("",""+_relatif_time); 
      double scalex = (double) this.getWidth()/(double) movie.width(); 
      double scaley = (double) this.getHeight()/(double) movie.height(); 
      canvas.scale((float) scalex, (float) scaley); 
      movie.draw(canvas, (float) scalex, (float) scaley) 
     } 

     this.invalidate(); 
    } 
} 

当我得到一个大红色的窗,我可以看到,画布绘制,并与我增加了日志,我可以看到我的电影不是空的,并且有一个长度!

不幸的是,除了大红色的矩形外,没有任何东西出现在画布上,而且我测试过不同的gif文件。

任何想法,为什么这不工作?

回答

7

你可以看看我的图书馆源代码https://github.com/sbakhtiarov/gif-movie-view我们只是用它。

+0

太棒了!工作很好。 –

+0

我试过了你的代码,它确实在工作。问题在于动画不关心GIF帧的时间。如你所知,每帧都有毫秒的时间,动画师必须小心等待。你的课的实施简单地以一个恒定的速度播放其他帧。 – Colateral