使用字体库和TextView代替ImageView展示图片

来源:互联网 发布:apache 2.0 开源协议 编辑:程序博客网 时间:2024/05/01 18:43

新来的同事介绍了一项之前没用过的技术,使用字体库和TextView代替ImageView展示图片,虽然在项目中尝试了一段时间后我又给去掉了,但是觉得这个技术还是不错的。现在记录一下最最基本的用法,如果想在项目中使用,建议先看下亓斌这篇博客。

一般情况下我们展示图片在xml布局中都是用ImageView设置src来展示,比如:

<ImageView    android:layout_width="100dp"    android:layout_height="100dp"    android:src="@mipmap/share" /><ImageView    android:layout_width="100dp"    android:layout_height="100dp"    android:src="@mipmap/back" />

效果图:

这里写图片描述

现在我们使用TextView实现这种功能(非设置background):

  • 下载字体库:先把使用的图标加入到购物车,然后选择下载代码:
    这里写图片描述

    • 解压之后可以看到如下文件,我们只要iconfont.woff文件和demo_unicode就好了:
      这里写图片描述

    • 然后新建一个存放字体库的文件夹assert,把字体库文件放入里面:

这里写图片描述

  • 打开demo_unicode文件,根据图表和编码对应关系,把编码写入text内容里面即可:
    这里写图片描述
  • 现在来看布局文件,通过textColor和textSize改变颜色和大小,注意text后面跟的内容,不要缺少东西了,否则展示不出来图片:
  <TextView        android:textColor="#ff00ff"        android:id="@+id/tv_share"        android:layout_width="100dp"        android:layout_height="100dp"        android:text="&#xe624;"        android:textSize="34sp" />    <TextView        android:textColor="#ff0000"        android:id="@+id/tv_back"        android:layout_width="100dp"        android:layout_height="100dp"        android:text="&#xe625;"        android:textSize="48sp" />
  • 你以为这样就可以了?那你就错了,还不能少了如下的代码:

    TextView tv_share=(TextView) findViewById(R.id.tv_share);TextView tv_back=(TextView) findViewById(R.id.tv_back);tv_share.setTypeface(Typeface.createFromAsset(getAssets(),"iconfont.woff"));tv_back.setTypeface(Typeface.createFromAsset(getAssets(),"iconfont.woff"));

– 看效果:
这里写图片描述