2013-05-25 51 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