android textView 描邊效果
阿新 • • 發佈:2019-01-11
最近在android上搞一個帶描邊效果的TextView,網上搜索了下都是採用兩個TextView在一個layout中進行實現,但細想了下,如果我在一個TextView中讓其以不同的方式進行兩次描繪不就能夠達到效果了嗎?由於網上沒有看到和我類似的方法,故發出來和大家分享,由於只需要重寫protected void onDraw(Canvas canvas);方法即可,故只附上onDraw的實現:
private boolean m_bDrawSideLine = false; // 預設不採用描邊 /* (non-Javadoc) * @see android.widget.TextView#onDraw(android.graphics.Canvas) */ @Override protected void onDraw(Canvas canvas) { if (m_bDrawSideLine) { // 描外層 //super.setTextColor(Color.BLUE); // 不能直接這麼設,如此會導致遞迴 setTextColorUseReflection(Color.BLUE); m_TextPaint.setStrokeWidth(3); // 描邊寬度 m_TextPaint.setStyle(Style.FILL_AND_STROKE); //描邊種類 m_TextPaint.setFakeBoldText(true); // 外層text採用粗體 m_TextPaint.setShadowLayer(1, 0, 0, 0); //字型的陰影效果,可以忽略 super.onDraw(canvas); // 描內層,恢復原先的畫筆 //super.setTextColor(Color.BLUE); // 不能直接這麼設,如此會導致遞迴 setTextColorUseReflection(Color.RED); m_TextPaint.setStrokeWidth(0); m_TextPaint.setStyle(Style.FILL_AND_STROKE); m_TextPaint.setFakeBoldText(false); m_TextPaint.setShadowLayer(0, 0, 0, 0); } super.onDraw(canvas); } private void setTextColorUseReflection(int color) { Field textColorField; try { textColorField = TextView.class.getDeclaredField("mCurTextColor"); textColorField.setAccessible(true); textColorField.set(color); textColorField.setAccessible(false); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } m_TextPaint.setColor(color); }
以上程式碼中m_bDrawSideLine為false即和一般的textView無異,只需要將其改為true即可看到描邊效果。以上,我只是拋磚引玉,以下發一個小圖吧。