android播放gif 我研究過3種
第一 :GifView支持android播放gif,效果是 先加載第一幀,而後慢慢加載完其餘的針,這樣效果視覺很很差,是從模糊到清晰的過程;
第二:是流行的把gif圖片經過工具分拆成n幀,而後使用逐幀動畫播放,我感受很麻煩的樣子;
第三 :使用Movie提供的Movie.decodeStream()方法解析gif,而後經過文件流的方式播放,效果特別好 ,和原圖片沒差
研究以後能夠經過canvas實現對gif的拉伸,適配任何屏幕。
核心代碼 本身加個layout,Activity測試
public class GifView extends View {
private Movie mMovie;
private long mMovieStart;
private int mWidth, mHeight;
private int mViewWidht, mViewHeight;
private OnPlayListener onPlayListener;
public GifView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public GifView(Context context) {
super(context);
mMovie = Movie.decodeStream(getResources().openRawResource(
R.raw.gif_anim));
}
public GifView(Context context, AttributeSet attrs) {
super(context, attrs);
//使用Movie解析gif圖片
mMovie = Movie.decodeStream(getResources().openRawResource( R.raw.gif_anim));
//得到屏幕寬度,高度
mWidth = BaseApplication.getInstance().screenWidth;
mHeight = BaseApplication.getInstance().screenHeight;
//gif圖片寬度,高度
mViewHeight = mMovie.height();
mViewWidht = mMovie.width();
}
public OnPlayListener getOnPlayListener() {
return onPlayListener;
}
public void setOnPlayListener(OnPlayListener onPlayListener) {
this.onPlayListener = onPlayListener;
}
boolean isDraw = true;
public void onDraw(Canvas canvas) {
long now = android.os.SystemClock.uptimeMillis();
if (isDraw) {
if (mMovieStart == 0) { // first time
mMovieStart = now;
}
if (mMovie != null) {
int dur = mMovie.duration();
if (dur == 0) {
dur = 5000;
}
//計算gif播放時間,gif播放完成,關閉界面
if (now - mMovieStart >= dur) {
isDraw = false;
if (onPlayListener != null) {
onPlayListener.onFinished();
}
}
int relTime = (int) ((now - mMovieStart) % dur);
mMovie.setTime(relTime);
//根據屏幕大小計算縮放比例
float saclex = (float) mWidth / (float) mViewWidht;
float sacley = (float) mHeight / (float) mViewHeight;
float sameRate = saclex > sacley ? saclex : sacley;
canvas.scale(sameRate, sameRate);
mMovie.draw(canvas, 0, 0);
invalidate();
}
}
}
//gif關閉接口
public static interface OnPlayListener {
public void onFinished();
}
}android