Android 中 Iconfont 圖標的使用以及自定義

本文為菜鳥窩作者 吳威龍 投稿

菜鳥窩是專業的程序猿在線學習平臺,提供最系統的 Android 項目實戰課程

如需轉載,請聯系菜鳥窩公眾號(cniao5),并注明出處。

前言

上篇文章《在 Android 中使用 SVG 矢量圖》簡單介紹了 SVG 圖片的好處以及如何在 Android 中使用 SVG 圖片。本文接著介紹下如何在 Android 中使用阿里巴巴 Iconfont 平臺的圖片,方便我們日常的開發。

SVG to VectorDrawable

從阿里巴巴矢量圖庫 Iconfont 可以下載 SVG 形式的圖片,導入 AS 中就轉為了 VectorDrawable 形式的圖片文件。如果不了解的可以看回我上一篇文章《在 Android 中使用 SVG 矢量圖》。

但是每次都需要下載 SVG 文件,再通過 AS 導入,也許算是挺麻煩的一件事情。現在推薦一個好工具,就是 SVG to VectorDrawable,顧名思義,就是一個把 SVG 文件 轉為 VectorDrawable 文件的工具。

只需要把 SVG 文件粘貼進去,該工具就會自動幫你轉為 VectorDrawable 文件。最后你只需要在 AS 中新建個文件,然后粘貼轉換后的 VectorDrawable 文件內容就去即可。當然,可能你覺得這樣并不方便,那就見仁見智了。

網址:http://inloop.github.io/svg2android/

使用 Iconfont 制作“圖片”字體文件的優點

更方便的使用 SVG 圖片
把圖標當成字符使用,大小和顏色都可以隨意改。

制作步驟

step1:

從 iconfont 平臺選擇要使用到的圖標(如圖),并下載(選擇下載代碼)至本地;復制字體文件到項目 assets 目錄;


image
image

step2:

打開下載下來的文件,并在目錄中打開 demo_unicode.html,找到圖標相對應的 HTML 實體字符碼


image
image

step3:

打開 res/values/strings.xml,把 demo_unicode.html 各個圖標的 字符嗎 添加到 string 值;

如:

<string name="all"></string>
<string name="back"></string>
<string name="cart"></string>
<string name="category"></string>
<string name="close"></string>
<string name="comments"></string>
<string name="cry"></string>

step4:

比如使用 圖標 cart,
打開 activity_main.xml,添加 string 值到 TextView:

<TextView
    android:id="@+id/like"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/cart" />

對該 TextView 設置顏色、大小就等同于給圖標 cart 設置顏色、大小。而且還不用考慮分辨率問題。

step5:

為 TextView 指定字體庫:

import android.graphics.Typeface; 
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont/iconfont.ttf");
    TextView textview = (TextView)findViewById(R.id.like);
    textview.setTypeface(iconfont);
}

通過以上 5 步,就可以實現目的了。但如果你還是覺得不夠方便,那么看下面這個第三方庫吧!

引入 Android-Iconics

以上有點麻煩:使用第三方庫:Android-Iconics 吧。
原理和之前講的一樣,只是把過程封裝了起來。

github

https://github.com/mikepenz/Android-Iconics

這個庫的好處:

image
image

意思就是可以使用不同的 icons 在不同的大小,不同的顏色以及不同的分辨率條件下已依然表現出色。

What do you get

  • No customization limitations (size, color, contour, background, padding, positioning, ...)
  • One icon source (no more mdpi, hdpi, ...)
  • Flexibility
  • If it takes a Drawable, it will also work with the IconicsDrawable!
  • Save in APK size
  • All licenses included, best used with AboutLibraries

相信上面的特色大家都看的懂,我也就不翻譯了

Already available fonts

  1. Google Material Design Icons
  2. Material Design Iconic Font
  3. Fontawesome
  4. Meteocons
  5. Octicons
  6. Community Material
  7. Weather Icons
  8. Typeicons
  9. Entypo
  10. Devicon
  11. Foundation Icons
  12. Ionicons

可用的字體圖標風格庫。

更多詳細的介紹請看官方介紹哈。

如何使用?

如何使用這個第三方庫呢,其實 github 上的介紹已經非常簡單清楚了,大家可以根據上面的介紹一步一步的使用此庫。

這里簡單的記錄下使用步驟:

step1:添加 gradle 依賴

compile "com.mikepenz:iconics-core:2.8.4@aar"

step2:選擇字體庫(添加一個喜歡的字體依賴庫就可以了)

compile 'com.mikepenz:google-material-typeface:3.0.1.0.original@aar'
compile 'com.mikepenz:material-design-iconic-typeface:2.2.0.2@aar'
compile 'com.mikepenz:fontawesome-typeface:4.7.0.0@aar'
compile 'com.mikepenz:octicons-typeface:3.2.0.2@aar'
compile 'com.mikepenz:meteocons-typeface:1.1.0.2@aar'
compile 'com.mikepenz:community-material-typeface:1.9.32.1@aar'
compile 'com.mikepenz:weather-icons-typeface:2.0.10.2@aar'
compile 'com.mikepenz:typeicons-typeface:2.0.7.2@aar'
compile 'com.mikepenz:entypo-typeface:1.0.0.2@aar'
compile 'com.mikepenz:devicon-typeface:2.0.0.2@aar'
compile 'com.mikepenz:foundation-icons-typeface:3.0.0.2@aar'
compile 'com.mikepenz:ionicons-typeface:2.0.1.2@aar'

step3:onCreate 中使用 LayoutInflaterCompat(不太懂,但是得這樣做)

Set the IconicsLayoutInflater as new LayoutInflaterFactory. This will enable automatic icon detection for TextViews,Buttons, and allow you to set icons on ImageView's via xml. This is compatible with libs which wrap the baseContext like Calligraphy. This does not work on FAB's please use the Context-Injection instead.(官方介紹)

@Override
protected void onCreate(Bundle savedInstanceState) {
    LayoutInflaterCompat.setFactory(getLayoutInflater(), new IconicsLayoutInflater(getDelegate()));
    //...
    super.onCreate(savedInstanceState);
    //...
}

step4:實際使用:代碼方式

官方提供了很多實現方式,這里只介紹一種,其他的感興趣可以去 github 上看。

 Drawable drawable =  new IconicsDrawable(this)
               .icon(FontAwesome.Icon.faw_android)
               .color(Color.RED)
               .sizeDp(24)

//可以隨意設置顏色、大小、圖標(圖標庫中的圖標)    

自定義的字體庫

其實就是換字體庫的意思,下面說說怎么自定義自己的字體文件。
主要的思路就是參考第三方框架寫自己的自定義 Iconfont,
還是用上面例子中所下載的字體文件作為自己的自定義字體文件庫。

按照 github 介紹可以分為以下幾個步驟:

step1:實現 ITypeface 接口,自定義 Font 類


public class CustomFont implements ITypeface {

    private static final String TTF_FILE = "iconfont.ttf";
    private static Typeface typeface = null;
    private static HashMap<String, Character> mChars;


    @Override
    public IIcon getIcon(String key) {
        return Icon.valueOf(key);
    }

    @Override
    public HashMap<String, Character> getCharacters() {
        if (mChars == null) {
            HashMap<String, Character> aChars = new HashMap<String, Character>();
            for (Icon v : Icon.values()) {
                aChars.put(v.name(), v.character);
            }
            mChars = aChars;
        }
        return mChars;
    }

    @Override
    public String getMappingPrefix() {
        return "custom";
    }

    @Override
    public String getFontName() {
        return "CustomFont";
    }

    @Override
    public String getVersion() {
        return "1.0.0";
    }

    @Override
    public int getIconCount() {
        return mChars.size();
    }

    @Override
    public Collection<String> getIcons() {
        Collection<String> icons = new LinkedList<String>();
        for (Icon value : Icon.values()) {
            icons.add(value.name());
        }
        return icons;
    }

    @Override
    public String getAuthor() {
        return "www.blog.csdn.net/leaf_130";
    }

    @Override
    public String getUrl() {
        return "http://blog.csdn.net/leaf_130";
    }

    @Override
    public String getDescription() {
        return "The premium icon font for Ionic Framework.";
    }

    @Override
    public String getLicense() {
        return "MIT Licensed";
    }

    @Override
    public String getLicenseUrl() {
        return "http://blog.csdn.net/leaf_130";
    }

    @Override
    public Typeface getTypeface(Context context) {
        if (typeface == null) {
            try {
                typeface = Typeface.createFromAsset(context.getAssets(),   TTF_FILE);
            } catch (Exception e) {
                return null;
            }
        }
        return typeface;
    }

    public enum Icon implements IIcon {


        //這里枚舉兩個圖標
        custom_all('\ue696'),
        custom_back('\ue697');


        char character;

        Icon(char character) {
            this.character = character;
        }

        public String getFormattedName() {
            return "{" + name() + "}";
        }

        public char getCharacter() {
            return character;
        }

        public String getName() {
            return name();
        }

        // remember the typeface so we can use it later
        private static ITypeface typeface;

        public ITypeface getTypeface() {
            if (typeface == null) {
                typeface = new CustomFont();
            }
            return typeface;
        }
    }


}

step2:自定義 Application 類(別忘了在配置文件配置)

public class MyApplication extends Application {


    @Override
    public void onCreate() {
        super.onCreate();


        //only required if you add a custom or generic font on your own
        Iconics.init(getApplicationContext());

        //register custom fonts like this (or also provide a font definition file)
        Iconics.registerFont(new CustomFont());
    }
}

step3:代碼中使用

public class IconActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        LayoutInflaterCompat.setFactory(getLayoutInflater(), new IconicsLayoutInflater(getDelegate()));
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_icon);


        Drawable drawable =  new IconicsDrawable(this)
                .icon(CustomFont.Icon.custom_all)
                .color(Color.BLACK)
                .sizeDp(50);


        ((ImageView)this.findViewById(R.id.img)).setImageDrawable(drawable);

    }
}


到這里已經實現了自定義 Iconfont 圖標的所有步驟。更多使用方式請看 Github 上作者給出的詳細說明文檔吧。

遇到的問題

自定義的 CustomFont,代碼中使用 ok,但是 xml 中使用不太行,暫時沒找到解決方法,可能是我使用出了問題,也可能是這個庫本身有點小 bug.

總結

上面論述了這么多,現在應該做個總結了,不然很快就忘了什么是 SVG ,什么是 Iconfont 圖標。

SVG 就是拉伸不影響像素的一種特殊的矢量圖,對頁面適配的支持性很強。使用阿里巴巴矢量圖庫 Iconfont 網站下載的圖標字體文件,在 Android 中使用將大大節省開銷,因為 15 個圖標的字體文件才 12k 左右。而之前的開發中一張圖片就上百 k,可謂大大降低了 apk 的大小。另外,使用字體文件的圖標,可以隨意設置大小、顏色等屬性,還能保證圖片的高保真度,而不會出現其他問題。

擼這個項目的一半,你就是大神 , 戳http://mp.weixin.qq.com/s/ZagocTlDfxZpC2IjUSFhHg

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容