Android Display gif animated pictures

Source: Internet
Author: User

Item (showgif) has been pushed to GitHub, see the link at the end of the article to download.

Displays a GIF animated image as follows:


Look at the effect in the demo:



button to pause and resume. Take a look at the Code logic implementation:

Package Com.zms.showgif;import Android.support.v7.app.actionbaractivity;import Android.os.bundle;import Android.view.menu;import Android.view.menuitem;import Android.view.view;import Android.widget.Button;public class    Main extends Actionbaractivity {private Gifimageview gifimageview;    Private Button Btnpause;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main);        Gifimageview = (Gifimageview) Findviewbyid (r.id.imggif);        Gifimageview.setmovieresource (R.RAW.SHOWME);        Btnpause = (Button) Findviewbyid (r.id.btnpause);    Btnpause.setonclicklistener (New Onclicklistenerimp ()); } Private class Onclicklistenerimp implements View.onclicklistener {@Override public void OnClick (View V {if (v = = btnpause) {if (gifimageview.ispaused ()) {Gifimageview.setpause                    D (FALSE); Btnpause.settext ("Pause");                    } else {gifimageview.setpaused (true);                Btnpause.settext ("Play"); }}}} @Override public boolean Oncreateoptionsmenu (Menu menu) {Getmenuinflater (). infl        Ate (R.menu.main, menu);    return true;        } @Override public boolean onoptionsitemselected (MenuItem item) {int id = item.getitemid ();        if (id = = r.id.action_settings) {return true;    } return super.onoptionsitemselected (item); }}

The core of the custom view:

Package Com.zms.showgif;import Android.content.context;import Android.content.res.typedarray;import Android.graphics.canvas;import Android.graphics.movie;import Android.os.build;import Android.util.AttributeSet; Import android.view.view;/** * Created by Alexzhou on 2015/1/29.    * 16:42 */public class Gifimageview extends View {//default is 1 seconds private static final int default_movie_duration = 1000;    private int Mmovieresourceid;    Private Movie Mmovie;    Private long Mmoviestart;    private int mcurrentanimationtime = 0;    private float Mleft;    private float mtop;    private float Mscale;    private int mmeasuredmoviewidth;    private int mmeasuredmovieheight;    Private Boolean mvisible = true;    Private volatile Boolean mpaused = false;    Public Gifimageview (Context context) {This (context, NULL);    } public Gifimageview (context context, AttributeSet Attrs) {This (context, attrs, R.styleable.gif_style); } public Gifimageview (context context, AttributeSetattrs, int defstyle) {Super (context, attrs, Defstyle);    Setviewattributes (context, attrs, Defstyle);         } private void Setviewattributes (context context, AttributeSet attrs, int defstyle) { if (Build.VERSION.SDK_INT >= build.version_codes.        Honeycomb) {setlayertype (view.layer_type_software, NULL);                }//Read the value of GIF from the description file, create a movie instance final TypedArray array = context.obtainstyledattributes (Attrs,        R.styleable.gif, Defstyle,-1);        Mmovieresourceid = Array.getresourceid (R.styleable.gif_resource,-1);        mpaused = Array.getboolean (r.styleable.gif_paused, false);        Array.recycle (); if (Mmovieresourceid! =-1) {Mmovie = Movie.decodestream (Getresources (). Openrawresource (MM        Ovieresourceid));        }} public int setmovieresource (int movieresid) {This.mmovieresourceid = Movieresid; Mmovie = Movie.decodestream (Getresources (). Openrawresource (Mmovieresourceid));        Requestlayout ();    return movieresid;        } public void Setmovie (movie movie) {This.mmovie = movie;    Requestlayout ();    } public Movie Getmovie () {return mmovie;        } public void Setmovietime (int time) {mcurrentanimationtime = time;    Invalidate (); }/** * Set pause * * @param paused */public void setpaused (Boolean paused) {this.mpaused = Paus        Ed        if (!paused) {Mmoviestart = Android.os.SystemClock.uptimeMillis ()-mcurrentanimationtime;    } invalidate ();    }/** * Determine if the GIF is stopped * * @return */public boolean ispaused () {return this.mpaused;            } @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {if (Mmovie! = null) {            int moviewidth = Mmovie.width ();            int movieheight = Mmovie.height (); int Maximumwidth = measurespec.getsize (Widthmeasurespec);            float Scalew = (float) moviewidth/(float) maximumwidth;            Mscale = 1f/scalew;            Mmeasuredmoviewidth = MaximumWidth;            Mmeasuredmovieheight = (int) (movieheight * mscale);        Setmeasureddimension (Mmeasuredmoviewidth, mmeasuredmovieheight);        } else {setmeasureddimension (Getsuggestedminimumwidth (), Getsuggestedminimumheight ()); }} @Override protected void OnLayout (Boolean changed, int l, int t, int r, int b) {super.onlayout (ch        Anged, L, T, R, b);        Mleft = (getwidth ()-mmeasuredmoviewidth)/2f;        Mtop = (getheight ()-mmeasuredmovieheight)/2f;    mvisible = getvisibility () = = view.visible;                } @Override protected void OnDraw (canvas canvas) {if (Mmovie! = null) {if (!mpaused) {                Updateanimationtime ();                Drawmovieframe (canvas);         Invalidateview ();   } else {drawmovieframe (canvas); }}} private void Invalidateview () {if (mvisible) {if (Build.VERSION.SDK_INT >= Build . Version_codes.            Jelly_bean) {postinvalidateonanimation ();            } else {invalidate ();        }}} private void Updateanimationtime () {Long now = Android.os.SystemClock.uptimeMillis ();        If first frame, record start time if (Mmoviestart = = 0) {Mmoviestart = now;        }//Take out the length of the animation int dur = Mmovie.duration ();        if (dur = = 0) {dur = default_movie_duration;    }//calculates the need to display the first few frames mcurrentanimationtime = (int) ((now-mmoviestart)% dur);        The private void Drawmovieframe (canvas canvas) {//sets the frame to be displayed and draws Mmovie.settime (Mcurrentanimationtime);        Canvas.save (Canvas.matrix_save_flag);        Canvas.scale (Mscale, Mscale);  Mmovie.draw (Canvas, Mleft/mscale, Mtop/mscale);      Canvas.restore ();        } @Override public void onscreenstatechanged (int screenstate) {super.onscreenstatechanged (screenstate);        mvisible = Screenstate = = screen_state_on;    Invalidateview (); } @Override protected void onvisibilitychanged (View changedview, int visibility) {super.onvisibilitychanged (        Changedview, visibility);        mvisible = visibility = = view.visible;    Invalidateview (); } @Override protected void onwindowvisibilitychanged (int visibility) {super.onwindowvisibilitychanged (Visibi        lity);        mvisible = visibility = = view.visible;    Invalidateview (); }}


Reprint Please specify source: Zhou Mushi's csdn blog Http://blog.csdn.net/zhoumushui

My github: Zhou Mushi's GitHub Https://github.com/zhoumushui


Android Display gif animated pictures

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.