今天在學習自定義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文件裏的字體,我們只需要添加我們用到的字體,防止文件太大,加載過慢。