Android 自定义Gif动画

/**
 * 自定义Gif动画 SurfaceView的实现主要是实现高速预览 我们将GIF图片绘制在SurfaceView上
 */
public class GifSurfaceView extends SurfaceView implements Callback {

    // 监听
    private SurfaceHolder holder;
    // 影片类
    private Movie movie;
    // 输入流
    private InputStream is = null;
    // 缩放
    private float zoom = 1f;
    // 图片路径
    private String path;
    // 判断是否网络读取
    private boolean isNet = false;

    // 逐步播放
    private Handler handler = new Handler();
    private Runnable run = new Runnable() {

        @Override
        public void run() {
            // 不断绘制
            Canvas canvas = holder.lockCanvas();
            // 绘制的时候进行缩放比例,不影响下次绘图操作
            canvas.save();
            canvas.scale(zoom, zoom);
            movie.draw(canvas, 0, 0);
            canvas.restore();
            holder.unlockCanvasAndPost(canvas);
            // 开始绘制
            movie.setTime((int) (System.currentTimeMillis() % movie.duration()));
            handler.removeCallbacks(run);
            // 下次还用这个线程
            handler.postDelayed(run, 30);
        }
    };

    // 构造方法
    public GifSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        holder = getHolder();
        holder.addCallback(this);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        try {
            // 判断读取方法
            if (isNet) {
                is = new URL(path).openConnection().getInputStream();
            } else {
                // 本地读取文件
                is = getContext().getAssets().open(path);
            }
            // 读取流
            movie = Movie.decodeStream(is);
            // 设置SurfaceView的宽高
            int width = movie.width();
            int height = movie.height();
            setMeasuredDimension((int) (width * zoom), (int) (height * zoom));
            // 播放gif的帧动画
            handler.post(run);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

   
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
       

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // SurfaceView被销毁时结束线程
        handler.removeCallbacks(run);
    }

    public void setZoom(float zoom) {
        this.zoom = zoom;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public void setNet(boolean isNet) {
        this.isNet = isNet;
    }

}

使用方式

GifSurfaceView gsv = (GifSurfaceView) findViewById(R.id.gif_view);
// 设置路径,这个路径实际上在自定义View中是可更改的,我们在assets目录下放置一张gif图片
gsv.setPath("anim.gif");
// 设置缩放大小
gsv.setZoom(2f);

你可能感兴趣的:(Android)