Android custom Gifview display gif animations

Source: Internet
Author: User

GIF animation is very much used in web development, using GIF, many animations do not have to be written by the program, now there are a lot of apps have been used to GIF animation, but the Android SDK does not provide us with GIF view, so we can only customize a view, To achieve the GIF effect.

Android does not provide us with ready-made Gifview, but provides us with the movie class, which is the key class used to implement Gifview. It has two most important methods, one is to set the current frame to be displayed according to the animation playing time. The second is to draw the currently displayed frame to the canvas. Take a look at the following:

You can also pause the GIF animation by clicking the Pause button.

Here's how it's implemented:

1. First customize the properties you need to use first: as shown in the following code:

<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable    name= "Gifcommon" >        <attr name= "gif_src" format= "reference"/>        <attr name= "Decode_stream" format= "boolean"/>        < attr name= "Default_animation_time" format= "integer"/>    </declare-styleable></resources>
The three attributes represent: GIF resource, whether the stream encoding is used, the default animation interval time.

2. Customize the Gifview code.

Package View;import Java.io.bytearrayoutputstream;import Java.io.inputstream;import android.content.context;import Android.content.res.typedarray;import Android.graphics.canvas;import Android.graphics.movie;import Android.util.attributeset;import android.view.view;import com.example.drawbaledemo.r;/** * @author rzq * */public        Class Gifview extends View {private Movie Mmovie;        /** * Animation start time/ private long mmoviestart;private Boolean mpaused = false; /** * Current frame animation time/ private int mcurrentanimationtime;/** * Custom three properties/&nbs p;private boolean decode_stream;private int src_id;private int Default_time;public Gifview (context context) {Super ( context); init (context, NULL);} Public Gifview (context context, AttributeSet set) {Super (context, set); Init (context, set);} private void init (context context, AttributeSet set) {TypedArray a = Context.obtainstyledattributes (set, R.styleable.gifcommon); src_id = A.getresourceId (R.STYLEABLE.GIFCOMMON_GIF_SRC,-1);d Ecode_stream = A.getboolean (R.styleable.gifcommon_decode_stream, true); Default_time = A.getinteger (r.styleable.gifcommon_default_animation_time, +); a.recycle (); setFocusable (true); Java.io.InputStream Is;is = Context.getresources (). Openrawresource (src_id); if (decode_stream) {Mmovie =    Movie.decodestream (IS); Creates a movier drawing object based on the file stream} else {byte[] array = streamtobytes (is); Mmovie = Movie.decodebytearray (array, 0, array.length);}} @Overrideprotected void OnDraw (canvas canvas) {if (Mmovie! = null) {if (!mpaused) {//Update frame Time updateanimationtime ();d Rawmovi Eframe (canvas); invalidate ();} else {//pause, frame time is not updated, only the current frame Drawmovieframe (canvas) is drawn;}}} private void Updateanimationtime () {Long now = Android.os.SystemClock.uptimeMillis ();//If first frame, record start time if (Mmoviestart = = 0 ) {Mmoviestart = now;} The time taken to take out the animation is int dur = mmovie.duration (); if (dur = = 0) {dur = Default_time;} Figure out the need to show the first few frames mcurrentanimationtime = (int) ((now-mmoviestart)% dur);} private void Drawmovieframe (canvas canvas{//Set the frame to be displayed, draw to Mmovie.settime (Mcurrentanimationtime); Canvas.save (Canvas.matrix_save_flag); Mmovie.draw (Canvas, 0, 0); Canvas.restore ();} /** * Set Pause * * @param paused */public void setpaused (Boolean paused) {this.mpaused = Paused;if (!paused) {/** * update animation start time */mmoviestart = Android.os.SystemClock.uptimeMillis ()-mcurrentanimationtime;} Invalidate ();} /** * Determine if the GIF is stopped * * @return */public boolean ispaused () {return this.mpaused;} /** * Override this method so that custom view supports wrap_content */@Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) { int widthmode = Measurespec.getmode (widthmeasurespec); int widthsize = Measurespec.getsize (widthmeasurespec); int Heightmode = Measurespec.getmode (heightmeasurespec); int heightsize = Measurespec.getsize (heightMeasureSpec); int Width;int height;if (Widthmode = = measurespec.exactly) {width = widthsize;} else {int desired = (int) (Getpaddingleft () + Mmovie.width () + getpaddingright ()); width = math.min (desired,widthsize);} if (Heightmode = = Measurespec.exactly) {height = heightsize;} else {int desired = (int) (Getpaddingtop () + mmovie.height () + getpaddingbottom ()); height = Math.min (desired,heightsize);} Setmeasureddimension (width, height);}  /** * will flow into a byte array * * @param is * @return */private static byte[] Streamtobytes (InputStream is) {Bytearrayoutputstream OS = New Bytearrayoutputstream (1024x768); byte[] buffer = new Byte[1024];int len;try {while (len = is.read (buffer)) >= 0) {OS.W Rite (buffer, 0, Len);}} catch (Java.io.IOException e) {}return os.tobytearray ();}}
3. Use Gifview in the layout file.

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    xmlns:gif=" Http://schemas.android.com/apk/res-auto "    android:layout_width=" Match_parent "    android:layout_height=" match_parent "    android:background=" #fed952 "    android:gravity=" Center ">    <view. Gifview        android:id= "@+id/gif_view"        android:layout_width= "wrap_content"        android:layout_height= "wrap _content "        android:background=" #ffffff "        gif:decode_stream=" true "        gif:default_animation_time=" "        gif:gif_src=" @drawable/animated_gif "/>    <textview        android:id=" @+id/btn "        Android : layout_width= "wrap_content"        android:layout_height= "wrap_content"        android:layout_below= "@+id/gif_ View "        android:text=" Pause "/></relativelayout>
As with normal view, the required resources are passed in.


Android custom Gifview display gif animations

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.