<span style= "font-family:kaiti_gb2312; Background-color:rgb (255, 255, 255); " > Today we look at how to display GIF animated images on Android phones. </span>
The first step is to create a custom view in the SRC directory with the following code:
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 to start playing a GIF image private Long Moviestart = 0;//movie Object manages multiple frames inside a GIF picture 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 ();//First time play if (Moviestart = = 0) {moviestart = currenttime;} Loop play if (movie! = null) {int duration = movie.duration (); int reltime = (int) ((currenttime-moviestart)% duration); movi E.settime (Reltime); Movie.draw (canvas, 0, 0);//force redraw invalidate ();} If you want to play only once, just determine that the value of Currenttime-moviestart is greater than duration and will not redraw super.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:
The entire sample project file download Link:
Android Display GIF pictures