Android基礎篇之顯示GIF格式圖片
2011-05-25 23:20:17
大家都知道,如果我們在Android中用ImageView直接顯示GIF的圖片,圖片只會停在第一幀上,而不會繼續。這時看到的只是一張靜態圖片,沒有GIF的效果。我們可以用Movie來顯示圖片 這個方法較簡單;
1.在main.xml中添加ImageView,指定一張GIF圖片為背景;
2.MainActivity.java
package com.yin.displayGIF;</p><p>import android.app.Activity;<br />import android.content.Context;<br />import android.graphics.Canvas;<br />import android.graphics.Movie;<br />import android.os.Bundle;<br />import android.view.View;</p><p>public class MainActivity extends Activity {<br />private MyCustomView mView;<br />private Movie mMovie;<br />private long mMovieStart;</p><p> public void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> mView = new MyCustomView(this);</p><p> setContentView(mView);<br /> }</p><p> //自訂一個類,繼承View<br /> class MyCustomView extends View{</p><p>public MyCustomView(Context context) {<br />super(context);<br />//以檔案流的方式讀取檔案<br />mMovie = Movie.decodeStream(<br />getResources().openRawResource(R.drawable.my_picture));<br />}</p><p>@Override<br />protected void onDraw(Canvas canvas) {</p><p>long curTime = android.os.SystemClock.uptimeMillis();<br />//第一次播放<br />if(mMovieStart == 0){<br />mMovieStart = curTime;<br />}</p><p>if(mMovie != null){<br />int duration = mMovie.duration();</p><p>int relTime = (int)((curTime - mMovieStart)% duration);<br />mMovie.setTime(relTime);<br />mMovie.draw(canvas, 0, 0);</p><p>//強制重繪<br />invalidate();</p><p>}</p><p>super.onDraw(canvas);<br />}<br /> }</p><p>}