文字添加虚线下划线

3,598 阅读3分钟

目前相关文字下方添加虚线的文章非常少,备选方案有:

  1. 文字下方添加一个drawable实现虚线样式 
  2. 通过spannable方案自定义
  3. 通过textview的getpaint实现
  4. 实现自定义并绘制
最后还是选择第四种方案,因为前三种方案基本没有相关参数能设置虚线,第一种能实现,但是无法判断当前文字长度,很难控制虚线绘制长度,如果采用点9,会导致拉伸问题。废话不多说了,直接上代码。


1)自定义DashTextView继承TextView.如果有实现换肤功能的朋友,TextView替换成SkinCompatTextView如下

public class DashTextView extends SkinCompatTextView {

2)先初始化画笔,并设置虚线离文字的间距。画笔样式就不多说了,颜色,线条粗细,虚线长短和间隙等。

private void initPaint(){
    mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    //默认使用textview当前颜色
    mPaint.setColor(getResources().getColor(color));
    mPaint.setStrokeWidth(3);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setPathEffect(new DashPathEffect(new float[] {5, 5}, 0));
    mPath = new Path();
    //设置虚线距离
    setPadding(0,0,0,3);
}

3)绘制线条

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    setLayerType(LAYER_TYPE_SOFTWARE, null);
    int centerY = getHeight();
    mPath.reset();
    mPath.moveTo(0, centerY);
    mPath.lineTo(getWidth(), centerY);
    canvas.drawPath(mPath, mPaint);
}

将画笔moveTo坐标x=0,y=getHeight()处,通过lineTo标记画线终点x=getWidth(),y不变。最后直接drawPath基本告成。

看似完美,但是有一个问题显露出来,就是textview的长度并不代表文字的长度,例如换行,如果一个英文单词过长,会导致右边留下非常长的一片空白区域,但是虚线在空白区域也会绘制。所以为了解决解决这个问题,我们就必须知道文字长度,而且是每行文字长度,然后取出最大长度绘制虚线。

//获取每行长度,选取最大长度。因为部分手机换行导致虚线过长
private float getTextWidth(){
    float textWidth = 0;
    //循环遍历打印每一行
    for (int i = 0; i < getLineCount(); i++) {
        if(textWidth < getLayout().getLineWidth(i)){
            textWidth = getLayout().getLineWidth(i);
        }
    }
    return textWidth == 0 ? getWidth() : textWidth;
}

将getWidth()换成getTextWidth(),自适应虚线长度等同于最长那行的文字长度。

最后就是实现点击功能了,以点击文字,跳出弹窗给出文字内容为例子,我们可以自定义想要的属性

<declare-styleable name="DashTextView">
    <attr name="title" format="string"/>
    <attr name="tips" format="string"/>
    <attr name="color" format="color"/>
    <attr name="dash" format="boolean"/>
</declare-styleable>

title:弹窗的标题

tips:弹窗的内容

color:虚线的颜色

dash: 是否显示虚线。有些虚线可能是加在adapter中,这个时候可以通过这个来控制是否显示虚线。

初始化这些自定义属性

private void initView(Context context,AttributeSet attrs){
    color = R.color.gray;
    if(attrs != null){
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DashTextView);
        //点击弹窗标题
        if (typedArray.hasValue(R.styleable.DashTextView_title)) {
            title = typedArray.getString(R.styleable.DashTextView_title);
        }
        //点击弹窗内容
        if (typedArray.hasValue(R.styleable.DashTextView_tips)) {
            tips = typedArray.getString(R.styleable.DashTextView_tips);
        }
        //虚线颜色
        if (typedArray.hasValue(R.styleable.DashTextView_color)) {
            color = typedArray.getResourceId(R.styleable.DashTextView_color,R.color.text_trans_gray3);
        }
        //是否显示虚线
        if (typedArray.hasValue(R.styleable.DashTextView_dash)) {
            dash = typedArray.getBoolean(R.styleable.DashTextView_dash,true);
        }
    }
    initPaint();
    setOnClickListener(v -> {
        new CommonAlertDialog(context).showTipsDialog(TextUtils.isEmpty(title) ? getText().toString() : title,tips);
    });
}

已经完成了。最后把完整代码贴上,方便大家研究和拓展。

public class DashTextView extends SkinCompatTextView {

    private Paint mPaint;
    private Path mPath;
    private String tips;
    private String title;
    private int color;
    private boolean dash = true;//默认有虚线

    public DashTextView(Context context) {
        super(context);
    }

    public DashTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context,attrs);
    }

    public DashTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context,attrs);
    }

    private void initView(Context context,AttributeSet attrs){
        color = R.color.gray;
        if(attrs != null){
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DashTextView);
            //点击弹窗标题
            if (typedArray.hasValue(R.styleable.DashTextView_title)) {
                title = typedArray.getString(R.styleable.DashTextView_title);
            }
            //点击弹窗内容
            if (typedArray.hasValue(R.styleable.DashTextView_tips)) {
                tips = typedArray.getString(R.styleable.DashTextView_tips);
            }
            //虚线颜色
            if (typedArray.hasValue(R.styleable.DashTextView_color)) {
                color = typedArray.getResourceId(R.styleable.DashTextView_color,R.color.gray);
            }
            //是否显示虚线
            if (typedArray.hasValue(R.styleable.DashTextView_dash)) {
                dash = typedArray.getBoolean(R.styleable.DashTextView_dash,true);
            }
        }
        initPaint();
        setOnClickListener(v -> {
            new CommonAlertDialog(context).showTipsDialog(TextUtils.isEmpty(title) ? getText().toString() : title,tips);
        });
    }

    private void initPaint(){
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        //默认使用textview当前颜色
        mPaint.setColor(getResources().getColor(color));
        mPaint.setStrokeWidth(3);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setPathEffect(new DashPathEffect(new float[] {5, 5}, 0));
        mPath = new Path();
        //设置虚线距离
        setPadding(0,0,0,3);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        setLayerType(LAYER_TYPE_SOFTWARE, null);
        int centerY = getHeight();
        mPath.reset();
        mPath.moveTo(0, centerY);
        mPath.lineTo(getTextWidth(), centerY);
        canvas.drawPath(mPath, mPaint);
    }

    //获取每行长度,选取最大长度。因为部分手机换行导致虚线过长
    private float getTextWidth(){
        float textWidth = 0;
        //循环遍历打印每一行
        for (int i = 0; i < getLineCount(); i++) {
            if(textWidth < getLayout().getLineWidth(i)){
                textWidth = getLayout().getLineWidth(i);
            }
        }
        return textWidth == 0 ? getWidth() : textWidth;
    }

}

在使用的时候

<包名.view.DashTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:tips="弹窗内容"
    app:title="弹窗标题"
    android:text="文字内容"/>

希望对大家有所帮助,谢谢!