load drawable from resource id - Android Graphics

Android examples for Graphics:Drawable

Description

load drawable from resource id

Demo Code


//package com.java2s;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

public class Main {
    /**//from  w  w w  .  j  av  a2s.c o m
     * load drawable from resource id
     *
     * @param rsrc
     * @param resid
     * @return
     */
    static public Drawable loadDrawableFromResource(Resources rsrc,
            int resid) {
        // load from resource
        Movie movie = Movie.decodeStream(rsrc.openRawResource(resid));
        if ((movie != null) && movie.duration() > 0) {
            return makeMovieDrawable(rsrc, movie);
        } else {
            // not animated GIF
            return rsrc.getDrawable(resid);
        }
    }

    /**
     * make AnimationDrawable from Movie instance
     *
     * @param rsrc
     * @param movie
     * @return
     */
    static private Drawable makeMovieDrawable(Resources rsrc, Movie movie) {
        int duration = movie.duration();
        int width = movie.width(), height = movie.height();

        AnimationDrawable result = new AnimationDrawable();
        result.setOneShot(false); // for loop

        Drawable frame = null;
        int start = 0;
        for (int time = 0; time < duration; time += 10) {
            if (movie.setTime(time)) {
                if (frame != null) {
                    // add previous frame
                    result.addFrame(frame, time - start);
                }

                // make frame
                Bitmap bitmap = Bitmap.createBitmap(width, height,
                        Bitmap.Config.RGB_565); // save heap
                //Bitmap.Config.ARGB_8888);   // high quality
                movie.draw(new Canvas(bitmap), 0, 0);
                frame = new BitmapDrawable(rsrc, bitmap);
                start = time;
            }
        }

        if (frame != null) {
            // add last frame
            result.addFrame(frame, duration - start);
        }
        return result;
    }
}

Related Tutorials