Android 字体设置 Typeface 设置

今天在学习自定义View当中遇到了一个Typeface属性,所以遇见问题,就学习一下。

Android 自带字体有四种属性:“sans”, “serif”, “monospace","normal"

第一种通过xml属性去设置:

android:typeface="monospace" //sans,serif,normal
第二种通过java代码去设置:
①第一种构造方法
view.setTypeface(typeface,typefaceStyle);

属性不明白看源码:
/**
     * Sets the typeface and style in which the text should be displayed,
     * and turns on the fake bold and italic bits in the Paint if the
     * Typeface that you provided does not have all the bits in the
     * style that you specified.
     *
     * @attr ref android.R.styleable#TextView_typeface
     * @attr ref android.R.styleable#TextView_textStyle
     */
    public void setTypeface(Typeface tf, int style) {
        if (style > 0) {
            if (tf == null) {
                tf = Typeface.defaultFromStyle(style);
            } else {
                tf = Typeface.create(tf, style);
            }

            setTypeface(tf);
            // now compute what (if any) algorithmic styling is needed
            int typefaceStyle = tf != null ? tf.getStyle() : 0;
            int need = style & ~typefaceStyle;
            mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0);
            mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0);
        } else {
            mTextPaint.setFakeBoldText(false);
            mTextPaint.setTextSkewX(0);
            setTypeface(tf);
        }
    }
两个参数含义:
typeface,就是一个Typeface 对象。 可以传空对象,若空对象就是走默认style
style,Typeface.NORMAL int值。

②另一个构造方法:
可以设置自定义的字体,对于在Android中引入其他字体,
要将字体文件保存在assets/fonts/目录下,字体文件有*.ttf和*.otf等格式
view.setTypeface(typeface);

Typeface typeface;

typeface = Typeface.createFromAsset(getAssets(), "fonts/regular.otf");//可以从assets中放入我们的自定义字体属性。

view.setTypeface(typeface);
看源码:
/**
     * Sets the typeface and style in which the text should be displayed.
     * Note that not all Typeface families actually have bold and italic
     * variants, so you may need to use
     * {@link #setTypeface(Typeface, int)} to get the appearance
     * that you actually want.
     *
     * @see #getTypeface()
     *
     * @attr ref android.R.styleable#TextView_fontFamily
     * @attr ref android.R.styleable#TextView_typeface
     * @attr ref android.R.styleable#TextView_textStyle
     */
    public void setTypeface(Typeface tf) {
        if (mTextPaint.getTypeface() != tf) {
            mTextPaint.setTypeface(tf);//给绘制TextView的画笔,设置字体属性

            if (mLayout != null) {//如果布局不为空
                nullLayouts();
                requestLayout();//刷新layout
                invalidate();//刷新View控件
            }
        }
    }

关于自定义的Android字体,在加载的过程中由于文件的大小可能会影响App性能,
可以把加载字体放在App启动时候去加载,把Typeface设成static,使用的时候直接调用即可。
关于fount文件里的字体,我们只需要添加我们用到的字体,防止文件太大,加载过慢。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章