ITeye博客

利用Movie播放GIF

wiseideal · 2013-05-09 16:52 · android · 移动开发 · Markdown

public class ViewContent extends View{

	Movie movie;
	long mStart;
	
	public ViewContent(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		InputStream is = getResources().openRawResource(R.drawable.g1);
		movie = Movie.decodeStream(is);
	}
	
	public ViewContent(Context context){
		this(context, null);
		setFocusable(true);
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		int duration = movie.duration();
		long now = android.os.SystemClock.uptimeMillis();
		if(mStart == 0){
			mStart = now;
		}
		movie.setTime((int) ((now - mStart) % duration));
		movie.draw(canvas,0, 0);
		invalidate();
	}

}

关键的地方有两处

 

1.

 

movie.setTime((int) ((now - mStart) % duration));

 此处设置播放gif的某一个时间的动画 单位为毫秒 这句话保证当前播放的都是对应当前时间的画面。

 

2.

movie.draw(canvas,0, 0);
invalidate();

 这里是绘制此gif的某一帧,并刷新本身,从而又调起了onDraw方法,如此动画的效果就达到了。

评论(1)

  1. #1 楼 · somefuture · 2015-10-29 22:57

    我每次走到movie.draw(canvas,0, 0); 这里就退出了 Fatal signal 11 (SIGSEGV) at 0x00000000 (code=1) 怎么搞呢

评论功能维护中,当前仅展示历史评论。