使用 ImageView 顯示 gif 影像檔

1 篇文章 / 0 new
author
使用 ImageView 顯示 gif 影像檔
此方式是利用 Movie 類別在 ImageView 來顯示 Gif動畫檔
public class MovieImageView extends ImageView {
    private Movie mMovie;
    private long mMovieStart;
    // ImageView 顯示式呼叫此方法, 若無宣告則會錯誤
    public MovieImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public void setImageFile(String filePath) {
        try {
            FileInputStream fStream = new FileInputStream(filePath);
            BufferedInputStream bis = new BufferedInputStream(fStream);
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;                
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }
            byte[] imageData = baf.toByteArray();
            mMovie = Movie.decodeByteArray(imageData, 0, imageData.length);
            invalidate();
            //
            baf.clear();
            bis.close();
            fStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onDraw(Canvas canvas) {   
        super.onDraw(canvas);
        long now = android.os.SystemClock.uptimeMillis();
        if (mMovieStart == 0) { // first time
            mMovieStart = now;
        }
        if (mMovie != null) {
            int dur = mMovie.duration();
            if (dur == 0) {
                dur = 1000;
            }
            int relTime = (int)((now - mMovieStart) % dur);               
            mMovie.setTime(relTime);
            mMovie.draw(canvas, 0, 0);
            invalidate();
        }
    }
}
注意, 此方式僅能撥放, 每一頁圖片大小均相同的格式, 也就是無壓縮的 gif檔
Free Web Hosting