使用SurfaceView播放gif动画


SurfaceView

SurfaceView一般会与SurfaceViewHolder(相当于SurfaceView的一个管家)结合使用,SurfaceHolder用于向与之关联的SurfaceView上绘图,SurfaceView.getHolder()。

SurfaceHolder提供了如下方法来获得Canvas对象。

Canvas lockCanvas();锁定S~w对象,获取其canvas。

Canvas lockCanvas(Rect dirty);锁定其上Rect划分的区域,获取其Canvas。

哦对了,,SurfaceHolder一般需要添加一个CallBack来获取SurfaceView的状态,因为SurfaceView什么时候绘制完我们是不知道的,需要他来告诉。

public class GifSurfaceView extends SurfaceView implements Callback {
	private SurfaceHolder holder ;
	private String path;
	private float scale;
	/**
	 * gif 动画绘制的开始坐标
	 */
	private int x;
	private int y ;
	
	Handler mHandler = new Handler();
	private Runnable run = new Runnable() {
		@Override
		public void run() {
			Canvas canvas = holder.lockCanvas();
			canvas.save();
			//进行缩放
			canvas.scale(1f/scale, 1f/scale);
			movie.draw(canvas, x, y);
			canvas.restore();
			holder.unlockCanvasAndPost(canvas);
			
			//设置时间:1 2 3 4 5   1 2 3 4 5 
			movie.setTime((int)(System.currentTimeMillis() % movie.duration()));
			mHandler.removeCallbacks(run);
			mHandler.postDelayed(run, 20);//让它不停的去画
			
		}
	};
	private Movie movie;//每一个gif可以看作一个小电影。
	
	
	
	public GifSurfaceView(Context context,String path) {
		super(context);
		holder = getHolder();// 电影的播放器
		holder.addCallback(this);
		this.path = path;
	}
	
	
	//surfaceView发生噶变
	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		
	}
	//surfaceView创建成功了
	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		initView();
	}
	/**
	 * 创建一个gif容器,同时根据容器的宽和高和gif的宽和高进行缩放并且居中
	 */
	private void initView() {
		try {
			movie = Movie.decodeStream(getContext().getAssets().open(path));
			int width = movie.width();
			int height = movie.height();
			
			float scaleX = width / (float)this.getWidth();//1  160/200.0=0
			float scaleY = height / (float)this.getHeight();
			/**
			 * 确定我们gif缩放的比列
			 * 
			 * gif图片 再surfaceView的居中显示
			 */
			if(scaleX>scaleY){
				x = 0 ;
				y = (int)((getHeight()*scaleX - height)/2);
				scale = scaleX;
				
			}else{
				y = 0 ;
				x = (int)((getWidth()*scaleY)/2);
				scale = scaleY;
			}
			
			mHandler.post(run);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}


	surfaceView销毁了
	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		mHandler.removeCallbacks(run);
	}

}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值