The implementation code for displaying GIF animation in Android _android

Source: Internet
Author: User
Tags current time set background visibility

This example describes the implementation code for displaying GIF animations in Android. Share to everyone for your reference, specific as follows:

GIF animation is still more commonly used in Android, such as Sina Weibo, there are many GIF pictures, and the display is very good, so I also want to get one. After my search data and collation, and finally out, in fact, there are many open source GIF github code, I downloaded a few, but are not very ideal, not what I completely want. So sometimes you have to learn to summarize, the open source of things organized into their own, now boring, also just have friends need, so now tidy up a bit, save later!

Nonsense not much to say, directly above the figure:

The main use here is the Android Android.graphics.Movie class, which is a very handy tool that Android offers us.

First, rewrite the control view to customize a gifview that displays the GIF image, as follows:

Package Net.loonggg.gif.view; 
Import NET.LOONGGG.GIF.R; 
Import Android.annotation.SuppressLint; 
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; 
  public class Gifview extends View {/** * defaults to 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 Gifview {This (context, NULL); Public Gifview (context, AttributeSet attrs) {This (context, attrs, R.styleable.customtheme_gifviewstyle) 
  ; 
  }Public Gifview (context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle); 
  Setviewattributes (context, attrs, Defstyle);  
    @SuppressLint ("Newapi") 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 GIF value from the description file to create a movie instance final TypedArray array = context.obtainstyledattributes (Attrs, R.STYLEABL 
    E.gifview, Defstyle, R.style.widget_gifview); 
    Mmovieresourceid = Array.getresourceid (R.styleable.gifview_gif,-1); 
    mpaused = Array.getboolean (r.styleable.gifview_paused, false); 
    Array.recycle (); if (Mmovieresourceid!=-1) {Mmovie = Movie.decodestream (Getresources (). Openrawresource (Mmovieresource 
    ID)); 
   }/** * Set GIF map resource * * @param movieresid */public void Setmovieresource (int movieresid) { This.mmovieresourceid = Movieresid; 
    Mmovie = Movie.decodestream (Getresources (). Openrawresource (Mmovieresourceid)); 
  Requestlayout (); 
    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 = paused 
    ; 
    if (!paused) {Mmoviestart = Android.os.SystemClock.uptimeMillis ()-mcurrentanimationtime; 
  } invalidate (); 
  /** * To determine whether the GIF has 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 (changed, 
    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) {update 
        Animationtime (); 
        Drawmovieframe (canvas); 
      Invalidateview (); 
      else {drawmovieframe (canvas); 
 } 
    } 
  } @SuppressLint ("Newapi") private void Invalidateview () {if (mvisible) {if (Build.VERSION.SDK_INT >= Bu Ild. Version_codes. 
      Jelly_bean) {postinvalidateonanimation (); 
      else {invalidate (); 
    }} private void Updateanimationtime () {Long now = Android.os.SystemClock.uptimeMillis (); 
    If the first frame, record starting time if (Mmoviestart = = 0) {Mmoviestart = now; 
    ///Remove the animation when the length int dur = Mmovie.duration (); 
    if (dur = = 0) {dur = default_movie_duration; 
  Mcurrentanimationtime = (int) ((now-mmoviestart)% dur) required to display the first few frames; 
    private void Drawmovieframe (Canvas Canvas) {//Set the frame to be displayed, Draw Mmovie.settime (mcurrentanimationtime); 
    Canvas.save (Canvas.matrix_save_flag); 
    Canvas.scale (Mscale, Mscale); 
    Mmovie.draw (Canvas, Mleft/mscale, Mtop/mscale); 
  Canvas.restore (); @SuppressLint ("Newapi") @Override public void onscreenstatechanged (int screenstate) {super.onscreenstatechanged (screenstate); 
    mvisible = Screenstate = = screen_state_on; 
  Invalidateview (); @SuppressLint ("Newapi") @Override protected void onvisibilitychanged (View changedview, int visibility) {s 
    Uper.onvisibilitychanged (Changedview, visibility); 
    mvisible = visibility = = view.visible; 
  Invalidateview (); } @Override protected void onwindowvisibilitychanged (int visibility) {super.onwindowvisibilitychanged (Visibili 
    TY); 
    mvisible = visibility = = view.visible; 
  Invalidateview (); } 
}

Movie actually manages multiple frames in a GIF animation, and only needs to settime () to draw the corresponding frame image at Draw (). Through the current time and duration between the conversion relationship, it is easy to achieve the effect of GIF animation.

Second, in the XML layout file, define this view in the following code:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
  android:layout_width=" fill_parent " 
  android:layout_height=" fill_parent " 
  android:o" rientation= "vertical" > 
  <net.loonggg.gif.view.gifview 
    android:id= "@+id/gif1" 
    android:layout_ Width= "100DP" 
    android:layout_height= "100DP" 
    android:layout_gravity= "Center_horizontal" 
    android: Enabled= "false"/> 
  <net.loonggg.gif.view.gifview 
    android:id= "@+id/gif2" 
    android:layout_ Width= "200DP" 
    android:layout_height= "200DP" 
    android:layout_gravity= "Center_horizontal" 
    android: Enabled= "false"/> 
</LinearLayout>

Finally, in Mainactivity, the code is as follows:

Package net.loonggg.gif; 
Import Net.loonggg.gif.view.GifView; 
Import android.app.Activity; 
Import Android.os.Bundle; 
public class Gif extends activity { 
  private gifview gif1, Gif2; 
  @Override public 
  void OnCreate (Bundle savedinstancestate) { 
    super.oncreate (savedinstancestate); 
    Setcontentview (r.layout.main); 
    GIF1 = (Gifview) Findviewbyid (R.ID.GIF1); 
    Set background gif picture resource 
    gif1.setmovieresource (r.raw.kitty); 
    Gif2 = (Gifview) Findviewbyid (R.ID.GIF2); 
    Gif2.setmovieresource (r.raw.b); 
    Set Pause 
    //gif2.setpaused (TRUE); 
  } 


Note: The only difference with ImageView and other view is that I added a GIF attribute.

<?xml version= "1.0" encoding= "Utf-8"?> 
<resources> 
  <declare-styleable name= "Gifview" > 
    <attr name= "gif" format= "reference"/> <attr name= "paused" 
    format= "boolean"/> 
  declare-styleable> 
  <declare-styleable name= "Customtheme" > <attr name= "Gifviewstyle" 
    Reference "/> 
  </declare-styleable> 
</resources>

This code has been very good, the use is very convenient, in fact, do not know what the meaning of the code can also be very good use, just to understand that I write the comments of the lines and activity inside the lines of code on it!

I hope this article will help you with the Android program.

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.