Android shows GIF images,
Today, we will study how to display GIF dynamic images on Android phones.
First, create a custom View under the src directory. The Code is as follows:
</pre><pre name="code" class="java">
</pre><pre name="code" class="java">
Import android. content. context; import android. graphics. canvas; import android. graphics. movie; import android. util. attributeSet; import android. view. view; public class MyGifView extends View {// indicates the absolute time for starting to play the GIF image private long movieStart = 0; // manage multiple frames in the GIF image using the movie object private Movie movie; public MyGifView (Context context, AttributeSet attrs) {super (context, attrs); movie = Movie. decodeStream (context. getResources () . OpenRawResource (R. drawable. horse) ;}@ Overrideprotected void onDraw (Canvas canvas) {long currentTime = System. currentTimeMillis (); // if (movieStart = 0) {movieStart = currentTime;} // loop playback if (movie! = Null) {int duration = movie. duration (); int relTime = (int) (currentTime-movieStart) % duration); movie. setTime (relTime); movie. draw (canvas, 0, 0); // force re-paint invalidate ();} // if you only want to play the video once, you only need to judge that the value of currentTime-movieStart is greater than duration and super will not be re-painted. onDraw (canvas );}}
Then write an Activity to display the GIF image:
import android.app.Activity;import android.os.Bundle;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}}
The XML layout file is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${relativePackage}.${activityClass}" > <com.example.gifdemo.MyGifView android:id="@+id/iv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="20dp" /></RelativeLayout>
As follows:
Download link of the entire sample project file:
Android display GIF images