之前北京一位Android開發人員發起翻譯Android API的倡議,集中國Android開發人員每一個人之力來不斷壯大,為一些英語水平一般無法全面理解原文Android API的開發人員提供一個橋樑。畢竟,語言不應當是開發人員的一個阻礙。
類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));
效果: