Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 文字描邊功能實作:自定義 StrokeTextView

編輯:關於 Android 程式設計

這裡也要簡單說明一下,這些小模塊並非我原創,而是當時查資料找到的,由於時間隔了比較久,原文鏈接已經記不清了,所以就不列出引用鏈接了。不過這些程式碼我都修改、完善過,也補充了一些註解,希望對大家有幫助。

文字描邊這個功能相當實用。如果是在單一背景下顯示文字,描邊能起到裝飾作用;而在複雜背景下——尤其是不同圖片背景上顯示文字時——由於文字顏色很容易和圖片背景相近,導致文字看不清、用戶體驗不佳。如果為文字加上不同顏色的描邊,讓文字輪廓是一種顏色、內部又是另一種顏色,那麼一般情況下,圖片要麼和輪廓顏色相近,要麼和內部顏色相近,這樣無論背景多麼複雜,文字都能清晰呈現。

我這裡採用的是重寫TextView的方式。

下面是相關程式碼,整體比較簡單,容易理解。

繼承的 TextView 文字描邊類如下:

 public class StrokeTextView extends TextView { private TextView outlineTextView = null; public StrokeTextView(Context context) { super(context); outlineTextView = new TextView(context); init(); } public StrokeTextView(Context context, AttributeSet attrs) { super(context, attrs); outlineTextView = new TextView(context, attrs); init(); } public StrokeTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); outlineTextView = new TextView(context, attrs, defStyle); init(); } public void init() { TextPaint paint = outlineTextView.getPaint(); paint.setStrokeWidth(3);// 描邊寬度 paint.setStyle(Style.STROKE); outlineTextView.setTextColor(Color.parseColor("#45c01a"));// 描邊顏色 outlineTextView.setGravity(getGravity()); } @Override public void setLayoutParams (ViewGroup.LayoutParams params) { super.setLayoutParams(params); outlineTextView.setLayoutParams(params); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // 設置輪廓文字 CharSequence outlineText = outlineTextView.getText(); if (outlineText == null || !outlineText.equals(this.getText())) { outlineTextView.setText(getText()); postInvalidate(); } outlineTextView.measure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onLayout (boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); outlineTextView.layout(left, top, right, bottom); } @Override protected void onDraw(Canvas canvas) { outlineTextView.draw(canvas); super.onDraw(canvas); } }

配置檔如下:

 <com.my.teststroketextview.StrokeTextView android:id="@+id/test_stroketextview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:textSize="25sp" android:textColor="@color/dark_gray" android:text="@string/hello_world" />

呼叫程式碼如下:

 private StrokeTextView test_stroketextview = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); test_stroketextview = (StrokeTextView)findViewById(R.id.test_stroketextview); test_stroketextview.setText("Hello world!"); } 

如果想更改文字描邊的寬度或顏色,需要修改上面的StrokeTextView類;當然,也可以把這個類設計得更靈活一些,這樣就能動態地修改描邊寬度或顏色了。

以上就是 Android 中文字描邊功能的實作範例,希望本文對大家學習 Android 開發有所幫助,也請大家多多支持本站。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved