新來的同事介紹了一項之前沒用過的技術,使用字體庫和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=""
android:textSize="34sp" />
<TextView
android:textColor="#ff0000"
android:id="@+id/tv_back"
android:layout_width="100dp"
android:layout_height="100dp"
android:text=""
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"));
– 看效果: