本文介绍如何将android-gif-drawable集成到项目中,并且如何使用android-gif-drawable加载离线和网络Gif动图。

转载请注明链接:http://blog.csdn.net/feather_wch/article/details/79558240

android-gif-drawable教程

版本:2018/3/14-1(17:56)

  • android-gif-drawable教程

    • android-gif-drawable的集成

      • 在线集成
      • 离线集成
    • android-gif-drawable的使用
      • 加载本地图片

        • GifDrawable
      • 加载网络Gif
    • 参考文献

  • Github:android-gif-drawable

android-gif-drawable的集成

在线集成

Github上相关教程,也比较简单,将依赖添加到项目的build.gradle文件即可:

dependencies {compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.11'
}

离线集成

Android Studio 3.0中有效

  1. 进入Github上的realease页面-realease点我

  2. 下载其中的android-gif-drawable-1.2.11.aar

  3. android-gif-drawable-1.2.11.aar添加到项目的libs目录中

  4. 在项目的build.gradle中添加该arr文件

compile(name:'android-gif-drawable-1.2.11', ext:'aar')
  1. 集成完毕,可以进行测试。

android-gif-drawable的使用

android-gif-drawable有四种控件:GifImageViewGifImageButtonGifTextViewGifTextureView。这里以ImageView为例进行介绍。

加载本地图片

  1. 直接在布局中选定资源文件
<pl.droidsonroids.gif.GifImageView
    android:id="@+id/fragment_gif_local"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/dog"/>
  1. 通过代码进行动态添加gif动图
//1. 构建GifDrawable
GifDrawable gifFromResDrawable = new GifDrawable( getResources(), R.drawable.dog );
//2. 设置给GifImageView控件
gifImageView.setImageDrawable(gifFromResDrawable);

GifDrawable

GifDrawable是用于该开源库的Drawable类。构造方法大致有9种:

//1. asset file
GifDrawable gifFromAssets = new GifDrawable( getAssets(), "anim.gif" );//2. resource (drawable or raw)
GifDrawable gifFromResource = new GifDrawable( getResources(), R.drawable.anim );//3. byte array
byte[] rawGifBytes = ...
GifDrawable gifFromBytes = new GifDrawable( rawGifBytes );//4. FileDescriptor
FileDescriptor fd = new RandomAccessFile( "/path/anim.gif", "r" ).getFD();
GifDrawable gifFromFd = new GifDrawable( fd );//5. file path
GifDrawable gifFromPath = new GifDrawable( "/path/anim.gif" );//6. file
File gifFile = new File(getFilesDir(),"anim.gif");
GifDrawable gifFromFile = new GifDrawable(gifFile);//7. AssetFileDescriptor
AssetFileDescriptor afd = getAssets().openFd( "anim.gif" );
GifDrawable gifFromAfd = new GifDrawable( afd );//8. InputStream (it must support marking)
InputStream sourceIs = ...
BufferedInputStream bis = new BufferedInputStream( sourceIs, GIF_LENGTH );
GifDrawable gifFromStream = new GifDrawable( bis );//9. direct ByteBuffer
ByteBuffer rawGifBytes = ...
GifDrawable gifFromBytes = new GifDrawable( rawGifBytes );

加载网络Gif

我们解决的办法是将Gif图片下载到缓存目录中,然后从磁盘缓存中获取该Gif动图进行显示。

1、下载工具DownloadUtils.java

public class DownloadUtils {private final int DOWN_START = 1; // Handler消息类型(开始下载)private final int DOWN_POSITION = 2; // Handler消息类型(下载位置)private final int DOWN_COMPLETE = 3; // Handler消息类型(下载完成)private final int DOWN_ERROR = 4; // Handler消息类型(下载失败)private OnDownloadListener onDownloadListener;public void setOnDownloadListener(OnDownloadListener onDownloadListener) {this.onDownloadListener = onDownloadListener;}/*** 下载文件** @param url      文件路径* @param filepath 保存地址*/public void download(String url, String filepath) {MyRunnable mr = new MyRunnable();mr.url = url;mr.filepath = filepath;new Thread(mr).start();}@SuppressWarnings("unused")private void sendMsg(int what) {sendMsg(what, null);}private void sendMsg(int what, Object mess) {Message m = myHandler.obtainMessage();m.what = what;m.obj = mess;m.sendToTarget();}Handler myHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case DOWN_START: // 开始下载int filesize = (Integer) msg.obj;onDownloadListener.onDownloadConnect(filesize);break;case DOWN_POSITION: // 下载位置int pos = (Integer) msg.obj;onDownloadListener.onDownloadUpdate(pos);break;case DOWN_COMPLETE: // 下载完成String url = (String) msg.obj;onDownloadListener.onDownloadComplete(url);break;case DOWN_ERROR: // 下载失败Exception e = (Exception) msg.obj;e.printStackTrace();onDownloadListener.onDownloadError(e);break;}super.handleMessage(msg);}};class MyRunnable implements Runnable {private String url = "";private String filepath = "";@Overridepublic void run() {try {doDownloadTheFile(url, filepath);} catch (Exception e) {sendMsg(DOWN_ERROR, e);}}}/*** 下载文件** @param url      下载路劲* @param filepath 保存路径* @throws Exception*/private void doDownloadTheFile(String url, String filepath) throws Exception {if (!URLUtil.isNetworkUrl(url)) {sendMsg(DOWN_ERROR, new Exception("不是有效的下载地址:" + url));return;}URL myUrl = new URL(url);URLConnection conn = myUrl.openConnection();conn.connect();InputStream is = null;int filesize = 0;try {is = conn.getInputStream();filesize = conn.getContentLength();// 根据响应获取文件大小sendMsg(DOWN_START, filesize);} catch (Exception e) {sendMsg(DOWN_ERROR, new Exception(new Exception("无法获取文件")));return;}FileOutputStream fos = new FileOutputStream(filepath); // 创建写入文件内存流,// 通过此流向目标写文件byte buf[] = new byte[1024];int numread = 0;int temp = 0;while ((numread = is.read(buf)) != -1) {fos.write(buf, 0, numread);fos.flush();temp += numread;sendMsg(DOWN_POSITION, temp);}is.close();fos.close();sendMsg(DOWN_COMPLETE, filepath);}interface OnDownloadListener{public void onDownloadUpdate(int percent);public void onDownloadError(Exception e);public void onDownloadConnect(int filesize);public void onDownloadComplete(Object result);}
}

2、调用DonwloadUtils进行下载,下载完成后加载本地图片

//1. 下载gif图片(文件名自定义可以通过Hash值作为key)
DownloadUtils downloadUtils = new DownloadUtils();
downloadUtils.download(gifUrlArray[0],getDiskCacheDir(getContext())+"/0.gif");
//2. 下载完毕后通过“GifDrawable”进行显示
downloadUtils.setOnDownloadListener(new DownloadUtils.OnDownloadListener() {@Overridepublic void onDownloadUpdate(int percent) {}@Overridepublic void onDownloadError(Exception e) {}@Overridepublic void onDownloadConnect(int filesize) {}//下载完毕后进行显示@Overridepublic void onDownloadComplete(Object result) {try {GifDrawable gifDrawable = new GifDrawable(getDiskCacheDir(getContext())+"/0.gif");mGifOnlineImageView.setImageDrawable(gifDrawable);} catch (IOException e) {e.printStackTrace();}}});
//获取缓存的路径
public String getDiskCacheDir(Context context) {String cachePath = null;if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())|| !Environment.isExternalStorageRemovable()) {// 路径:/storage/emulated/0/Android/data/<application package>/cachecachePath = context.getExternalCacheDir().getPath();} else {// 路径:/data/data/<application package>/cachecachePath = context.getCacheDir().getPath();}return cachePath;
}

参考文献

  1. android-gif-drawable移植
  2. android-gif-drawable的使用
  3. 网络加载gif图片

android-gif-drawable教程相关推荐

  1. android 图片 drawable,在android中Drawable图片使用教程

    在android项目的目录里面,res存放着各种资源,其中Drawable是android开发中使用最广泛的资源,它既可以直接用图片作为资源,也可以用xml文件.本文学习啦小编主要介绍在android ...

  2. 《Android UI基础教程》——1.2节Android 应用程序的基本结构

    本节书摘来自异步社区<Android UI基础教程>一书中的第1章,第1.2节Android 应用程序的基本结构,作者 [美]Jason Ostrander,更多章节内容可以访问云栖社区& ...

  3. Android ActionBarSherlock使用教程

    Android ActionBarSherlock使用教程 本文转自 http://www.chenwg.com/android/actionbarsherlock%E4%BD%BF%E7%94%A8 ...

  4. Android基础新手教程——3.4 TouchListener PK OnTouchEvent + 多点触碰

    Android基础新手教程--3.4 TouchListener PK OnTouchEvent + 多点触碰 标签(空格分隔): Android基础新手教程 本节引言: 如题,本节给大家带来的是To ...

  5. android真实项目教程(七)——梦醒边缘花落_by_CJJ

    大家下午好,我是CJJ,说说昨晚挑灯夜写毕业论文到凌晨三点多,当写到致谢词那块时,我违心的写下: " 本论文在xxx导师的悉 心指导和亲切关怀下完成的.导师渊博的专业知识.严谨的治学态度,精 ...

  6. android真实项目教程(六)——落叶醉赤壁_by_CJJ

    大家晚上好,我是cjj,今天不讲废话,因为我被"忙"了... 今晚主要把关于的界面(aboutFragment)完成了...效果很好哦 (自吹一下)...呵呵...其中有两个比较好 ...

  7. android真实项目教程(四)——MY APP MY STYLE_by_CJJ

    大家下午好...如果在学校,到时间吃晚饭了....隔了好久才重新敲代码...又落后那么多了,要更加努力学习了....今天下午写了下app的第四部分... 这里给下之前三部分的地址,因为如果第一次看,, ...

  8. android真实项目教程(三)——首页初点缀_by_CJJ

    大家晚上好,CJJ不好,前天打球,把右手弄脱臼了...搞得我现在只能一只手敲代码...那效率,我给自己跪了 ...写了好久,才写了那么一丁点...明明还有好多要说的...也只能等手好了再继续吧...呵 ...

  9. android真实项目教程(二)——漫画App初构_by_CJJ

    大家晚上好,我是CJJ,继昨天写好框架之后,今天上班一直在想做什么东西...本来想拿我即将要上交的毕业设计做教程的,但是想想好像在重复工作那样子....呵呵 ... 伟大的先人说过,不要重复制造轮子. ...

  10. android真实项目教程(一)——App应用框架搭建_by_CJJ

    大家好,我是CJJ,学android半年了,仍然是菜虫一只......为了进步,想把自己知道的知识和初学者分享,也希望路过的大神能给些意见....呵呵......开始今天的教程吧,晕,不敢说教程了 , ...

最新文章

  1. [导入]圣诞快乐,快乐圣诞。。。。。。
  2. 独家揭秘!阿里大规模数据中心的性能分析 1
  3. why always WebContent is added as prefix of url when repository request served
  4. SSM+easyUI(框架的搭建)
  5. 「Python-Django」django 实现将本地图片存入数据库,并能显示在web上
  6. (76)FPGA面试题-Verilog实现下降沿检测
  7. 头条搜索已经全面上线,会不会成为下一个流量风口
  8. ug链轮设计软件_正版UG软件,UG软件代理,正版UG软件模块功能介绍
  9. 一个按键控制数码管的开和关_单片机是否能用一个按键控制数码管的显示图?...
  10. 转:工具类之SpannableStringUtils(相信你会爱上它)
  11. java调用服务器打印机不登录_java – 从网络服务器打印到没有中介的热敏打印机...
  12. “数据类型不一致: 应为 NUMBER, 但却获得 BINARY”解决方法
  13. AIX虚拟内存管理机制(转)
  14. android ptp 源码分析,ptp增加豆瓣评分
  15. Python的模块和包管理
  16. 最新wifi大师小程序独立版3.0.8源码
  17. 大数据运维架构师培训(4):Oozie,Flume,Sqoop,Azkaban,Ranger
  18. 阿里云acp报名了可以退吗?阿里云acp认证所需具备的知识
  19. 谷歌(Google): reCaptcha(2.0版本)做网站验证码
  20. 【个人网页设计】简单大方

热门文章

  1. DoraCloud云教室实践
  2. mysql 错误1067_mysql服务1067错误多种解决方案分享
  3. html内容被背景图片遮住怎么办_css背景图片显示不完怎么解决?
  4. HTML与CSS——闪亮霓虹按钮(你值得拥有)(完整源码)
  5. Golang 获取http状态码
  6. windows10 浏览器出现无法连接到代理服务器
  7. 12306验证码已不再安全 机器准确率99.8%
  8. ubuntu 安装python编辑器 pycharm
  9. 个人内外网存储服务器(主要是外网ftp)完整解决方案
  10. Python从入门到实践:面向对象之封装(二)