android textView 描边效果

本文介绍了一种在Android中为TextView添加描边效果的独特方法,通过重写`onDraw`方法,避免使用两个TextView堆叠的方式。只需改变一个布尔值,就能轻松实现描边。这种方法简单高效,适合对TextView样式有个性化需求的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值