现在的位置: 首页 > 综合 > 正文

android textView 描边效果

2018年03月18日 ⁄ 综合 ⁄ 共 1459字 ⁄ 字号 评论关闭

        最近在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即可看到描边效果。以上,我只是抛砖引玉,以下发一个小图吧。

抱歉!评论已关闭.