類Typeface詳細規定了字體的字型和固有特性。當繪製(和量測)時,使用畫筆尤其是在任意使用像textSize, textSkewX, textScaleX用來指定文字顯示,這是很有幫助的。
演示範例(爲個人原創,當然遇見問題時參考了一些國內/國外的一些範例):
(1)創建佈局Layout
//創建線性佈局
LinearLayout linearLayout=newLinearLayout(this);
//設定線性佈局爲垂直方向
linearLayout.setOrientation(LinearLayout.VERTICAL);
//以該線性佈局做視圖
setContentView(linearLayout);
(2)針對正常字體
//普通正常字體
normal=newTextView(this);
//設置字體內容,請注意:目前Android主要針對拉丁語系可使用字型設定,中文暫不支持
normal.setText("Normal Font FYI");
//設置字體大小
normal.setTextSize(20.0f);
//設置字型爲默認,正常字體
normal.setTypeface(Typeface.DEFAULT,Typeface.NORMAL);
//增加該字體並顯示到佈局linearLayout中
linearLayout.addView(normal,newLinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
(3)針對粗體字體
//粗體字體
bold=newTextView(this);
bold.setText("Bold Font FYI");
bold.setTextSize(20.0f);
//設置字體顏色爲藍色
bold.setTextColor(Color.BLUE);
//設置字型爲默認粗體,粗體字體
bold.setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD);
linearLayout.addView(bold,newLinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
(4)針對斜體字體
//斜體字體
italic=newTextView(this);
italic.setTextSize(20f);
italic.setText("Italic Font FYI");
//設置字體顏色爲紅色
italic.setTextColor(Color.RED);
//設置字型爲等寬字型,斜體字體
italic.setTypeface(Typeface.MONOSPACE,Typeface.ITALIC);
linearLayout.addView(italic,newLinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
(5)針對粗斜體字體
//粗斜體字體
italic_bold=newTextView(this);
italic_bold.setTextSize(20f);
italic_bold.setText("Italic & Bold Font FYI");
//設置字體顏色爲黃色
italic_bold.setTextColor(Color.YELLOW);
//設置字型爲等寬字型,斜體字體
italic_bold.setTypeface(Typeface.MONOSPACE,Typeface.BOLD_ITALIC);
linearLayout.addView(italic_bold,newLinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
(6)針對中文仿“粗體”
//針對Android字型的中文字體問題
chinese=newTextView(this);
chinese.setText("中文粗體顯示效果");
//設置字體顏色
chinese.setTextColor(Color.MAGENTA);
chinese.setTextSize(20.0f);
chinese.setTypeface(Typeface.DEFAULT_BOLD, Typeface.BOLD);
//使用TextPaint的仿“粗體”設置setFakeBoldText爲true。目前還無法支持仿“斜體”方法
tp=chinese.getPaint();
tp.setFakeBoldText(true);
linearLayout.addView(chinese,newLinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
(7)自定義創建字型
//自定義字體字型
custom=newTextView(this);
//字體MgOpenCosmeticaBold.ttf放置於assets/font/路徑下
typeface=Typeface.createFromAsset(getAssets(),"font/MgOpenCosmeticaBold.ttf");
custom.setTypeface(typeface);
custom.setText("Custom Font FYI");
custom.setTextSize(20.0f);
//設置字體顏色
custom.setTextColor(Color.CYAN);
linearLayout.addView(custom,newLinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));