這里也要簡單說一下,這些小模塊并不是我原創(chuàng),也是當(dāng)時(shí)查資料找到的,由于時(shí)間比較久,原文鏈接已經(jīng)忘記了,所以這里就不列出引用鏈接了。不過這些代碼我都修改、完善過,也添加了一些注釋,希望對大家有幫助。
文字描邊這個(gè)功能挺實(shí)用的,如果是單一背景下顯示文字,文字描邊也可起到裝飾作用。如果是復(fù)雜背景下,尤其是在不同圖片背景下顯示文字,因?yàn)槲淖诸伾苋菀缀蛨D片背景相似,這樣導(dǎo)致文字看不清楚,用戶體驗(yàn)不佳。如果文字經(jīng)過不同顏色描邊后,文字輪廓部分一種顏色,文字內(nèi)部另一種顏色,因?yàn)橐话闱闆r下,圖片要么和文字輪廓顏色相近,要么和文字內(nèi)部顏色相近,這樣不管圖片背景多復(fù)雜,文字都會(huì)整體顯示。
我這里使用的方法是重寫TextView方式。
下面是相關(guān)代碼,整體比較簡單,很容易懂。
繼承的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); // 設(shè)置輪廓文字 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" />
調(diào)用代碼如下:
private StrokeTextView test_stroketextview = null; @Overrideprotected 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類,當(dāng)然也可以把這個(gè)類設(shè)計(jì)的更靈活些,這樣就可以動(dòng)態(tài)的修改描邊寬度或者描邊顏色。
以上就是android中文字描邊功能的實(shí)現(xiàn)實(shí)例,希望本文對大家學(xué)習(xí)android開發(fā)有所幫助。請大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選