我是靠谱客的博主 淡然蛋挞,最近开发中收集的这篇文章主要介绍Android显示Gif动图,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

package org.media.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Movie;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
import java.io.InputStream;
public class DrawingGif extends SurfaceView implements SurfaceHolder.Callback{
private final static String TAG = "DrawingGif";
private int scale = 1;
private String path;
private SurfaceHolder mHolder;
private Canvas canvas;
private Movie movie;
private Handler mHandler;
public DrawingGif(Context context) {
this(context,null);
}
public DrawingGif(Context context, AttributeSet attrs) {
this(context,attrs,0);
}
public DrawingGif(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init(){
Log.d(TAG,"init");
mHolder = getHolder();
mHolder.addCallback(this);
mHandler = new Handler();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated");
new Thread(mRunnable).start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.d(TAG,"surfaceChanged");
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d(TAG,"surfaceDestroyed");
mHandler.removeCallbacks(mRunnable);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.d(TAG,"onMeasure,path:"+path);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (!TextUtils.isEmpty(path)){
try {
InputStream ins = getContext().getAssets().open(path);
movie = Movie.decodeStream(ins);
int width = movie.width();
int height = movie.height();
setMeasuredDimension(width*scale,height*scale);
//mHandler.post(mRunnable);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private Runnable mRunnable = new Runnable() {
@Override
public void run() {
if (!TextUtils.isEmpty(path)){
canvas = mHolder.lockCanvas();
canvas.save();
canvas.drawColor(Color.WHITE);
canvas.scale(scale, scale);
movie.draw(canvas, 0, 0);
movie.setTime((int) (System.currentTimeMillis() % movie.duration()));
canvas.restore();
mHolder.unlockCanvasAndPost(canvas);
mHandler.postDelayed(mRunnable, 50);
}
}
};
public int getScale() {
return scale;
}
public void setScale(int scale) {
this.scale = scale;
invalidate();
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
invalidate();
}
}
使用:
gif = (DrawingGif) findViewById(R.id.gif);
gif.setPath("2.gif");//asset路径
gif.setScale(5);

最后

以上就是淡然蛋挞为你收集整理的Android显示Gif动图的全部内容,希望文章能够帮你解决Android显示Gif动图所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(46)

评论列表共有 0 条评论

立即
投稿
返回
顶部