package com.joyodream.common.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint.Style; import android.text.TextPaint; import android.util.AttributeSet; import android.view.ViewGroup; import android.widget.TextView; /** * * 描边,默认是灰色描边 * * @author lipeilong * */ public class JDStrokeTextView extends TextView { private TextView borderText = null; private final int STROKE_WIDTH = 6; // 线宽度 public JDStrokeTextView(Context context) { super(context); borderText = new TextView(context); init(); } public JDStrokeTextView(Context context, AttributeSet attrs) { super(context, attrs); borderText = new TextView(context,attrs); init(); } public JDStrokeTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); borderText = new TextView(context,attrs,defStyle); init(); } public void init(){ TextPaint tp1 = borderText.getPaint(); tp1.setStrokeWidth(STROKE_WIDTH); tp1.setStyle(Style.STROKE); borderText.setTextColor(0xff333333); borderText.setGravity(getGravity()); } @Override public void setLayoutParams (ViewGroup.LayoutParams params){ super.setLayoutParams(params); borderText.setLayoutParams(params); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { CharSequence tt = borderText.getText(); if(tt== null || !tt.equals(this.getText())){ borderText.setText(getText()); this.postInvalidate(); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); borderText.measure(widthMeasureSpec, heightMeasureSpec); } protected void onLayout (boolean changed, int left, int top, int right, int bottom){ super.onLayout(changed, left, top, right+STROKE_WIDTH, bottom); borderText.layout(left, top, right+STROKE_WIDTH, bottom);// 总要,否则会截断部分文字 } @Override protected void onDraw(Canvas canvas) { borderText.draw(canvas); super.onDraw(canvas); } } 网上找的几种解决方案中,这个是最靠谱的了。使用系统自带的阴影也是可以实现部分效果,看情况选择使用
时间: 2024-09-28 22:10:07