Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android- play animated gifs from a file

Tags:

android

gif

I have found tutorials about how to play animated gifs in android by reading it from an asset or using a drawable object. But what I want is to read a gif file from sdcard. I have changed the project reading gif from assets a little bit.

In the main activity, I basically create gifMovieView then setContent(gifMovieView) In the constructor of the GifMovieView class, I have initialized the Movie object like in the project "eu.andlabs.tutorial.animatedgifs". But I have used decodeFile giving the file path instead of decodeStream getting inputStream.

    File file = new File (Environment.getExternalStorageDirectory().getAbsolutePath(),"piggy.gif");

    if(file.exists()){

           mMovie = Movie.decodeFile(file.getPath()); 
   }

I HAVE GİVEN I/O EXCEPTION for this line. It finds the file but decodeFile gives exception.

In onDraw ;

@Override
protected void onDraw(Canvas canvas) {
    canvas.drawColor(Color.TRANSPARENT);
    super.onDraw(canvas);
    final long now = SystemClock.uptimeMillis();

    if (mMoviestart == 0) { 
        mMoviestart = now;
    }


    Log.i("",""+mMovie.duration());

    Log.i("",""+mMoviestart);

    final int relTime = (int)((now - mMoviestart) % mMovie.duration());
    mMovie.setTime(relTime);
    mMovie.draw(canvas, 10, 10);
    this.invalidate();
}

BECAUSE OF THE EXCEPTION, movie.duration becomes 0 causing the error.

Any suggestions?

Thank you in advance

https://gist.github.com/beyzakokcan/5488897/raw/e9c2afbf941d06ed0f1d3b75dc3d100ff9d7ee85/GifMovieView.java

like image 836
Beyza Avatar asked Jan 18 '26 05:01

Beyza


1 Answers

Use animation:

1 - Extract your gif in Link and save images in drawable folder

2 - Create image_background_animation.xml in drawable folder, where "img_weel" is a image extracted from gif:

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false" >

    <item
        android:drawable="@drawable/img_weel_1"
        android:duration="100"/>
    <item
        android:drawable="@drawable/img_weel_2"
        android:duration="100"/>
    <item
        android:drawable="@drawable/img_weel_3"
        android:duration="100"/>

</animation-list>

3 - In java code:

ImageView imgWheel = (ImageView) findViewById(R.id.img_wheel);
imgWheel.setBackgroundResource(R.drawable.image_background_animation);

AnimationDrawable frameAnimation = (AnimationDrawable) imgWheel.getBackground();
frameAnimation.start();

4 - If you want determinate time of animation:

new CountDownTimer(3000, 100) {
 void onFinish() {
    frameAnimation.stop();
  }
}.start();

Look here

like image 79
andrehsouza Avatar answered Jan 19 '26 19:01

andrehsouza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!