Display GIF animation in Android

Source: Internet
Author: User

Gif animation is often used in android. For example, there are many gif images in Sina Weibo and they are displayed very well, so I also want to get one. After searching materials and sorting by multiple parties, I finally got it out. In fact, there are a lot of open-source gif display code on github. I have downloaded a few, but they are not ideal, not exactly what I want. So sometimes you have to learn to sum up and organize open-source things into your own. Now it's boring, and there's just a need for friends. So now I 've sorted it out and kept it for future use!

Not to mention nonsense, direct:


Here we mainly use the android. graphics. Movie class in android, which is a very convenient tool provided by android.

First, override the control View to customize a gif View. The Code is 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 {/*** default value: 1 second */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 (Context context) {this (context, null);} public GifView (Context cont Ext, AttributeSet attrs) {this (context, attrs, R. styleable. customTheme_gifViewStyle);} public GifView (Context 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) {setL AyerType (View. LAYER_TYPE_SOFTWARE, null);} // read the gif value from the description file and create a Movie instance final TypedArray = context. obtainStyledAttributes (attrs, R. styleable. 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 (mMovieResourceId);}/*** set gif image 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 () {re Turn 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 ();}/*** determines whether the gif image has stopped ** @ return */public boolean isPaused () {return this. mPaused ;}@ Overrideprotected 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; interval = maximumWidth; mMeasuredMovieHeight = (int) (movieHeight * mScale ); setMeasuredDimension (mMeasuredMovieWidth, mMeasuredMovieHeight);} else {setMeasuredDimension (getSuggeste DMinimumWidth (), getSuggestedMinimumHeight () ;}@ Overrideprotected 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;} @ Overrideprotected void onDraw (Canvas canvas) {if (mMovie! = Null) {if (! MPaused) {updateAnimationTime (); drawMovieFrame (canvas); invalidateView ();} else {drawMovieFrame (canvas) ;}}@ SuppressLint ("NewApi") 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 the first frame is set, record the start time if (mMovieStart = 0) {mMovieStart = now;} // retrieves the animation duration int dur = mMovie. duration (); if (dur = 0) {dur = DEFAULT_MOVIE_DURATION;} // calculate the mCurrentAnimationTime = (int) (now-mMovieStart) % dur);} private void drawMovieFrame (Canvas canvas) {// you can draw mMovie by setting the frame to be displayed. setTime (mCurrentAnimationTime); canvas. save (Canvas. MATRIX_SAVE_FLAG); canvas. scale (mScale, mScale); mMovie. draw (canvas, mLeft/mScale, mTop/mScale); canvas. restore () ;}@ SuppressLint ("NewApi") @ Overridepublic void onScreenStateChanged (int screenState) {super. onScreenStateChanged (screenState); mVisible = screenState = enabled; invalidateView () ;}@ SuppressLint ("NewApi") @ Overrideprotected void onVisibilityChanged (View changedView, int visibility) {super. onVisibilityChanged (changedView, visibility); mVisible = visibility = View. VISIBLE; invalidateView () ;}@ Overrideprotected void onWindowVisibilityChanged (int visibility) {super. onWindowVisibilityChanged (visibility); mVisible = visibility = View. VISIBLE; invalidateView ();}}
Movie manages multiple frames in GIF animation. You only need to use setTime () to draw the corresponding image when draw. Through the Conversion Relationship between the current time and duration, it is easy to achieve GIF motion.

Second, define the view in the xml layout file. The Code is as follows:

 
     
      
  
 
Finally, the Code for using MainActivity 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; @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); gif1 = (GifView) findViewById(R.id.gif 1); // set the background GIF image resource gif1.setMovieResource (R. raw. kitty); gif2 = (GifView) findViewById(R.id.gif 2); gif2.setMovieResource (R. raw. b); // set pause // gif2.setPaused (true );}}
Note: The only difference between ImageView and other views is that I add a gif attribute.

 
     
                      
      
              
  
 
This code is very good and easy to use. In fact, it can be used well without understanding what the code means, you only need to know the lines I wrote comments and the lines of code in the Activity!
Reprinted please indicate the source: http://blog.csdn.net/loongggdroid/article/details/21166563

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.