通过使用这个类,您可以将虚线和下划线效果应用于多行文本。要使用DashPathEffect,您必须关闭TextView的硬件加速(尽管DashPathEffect方法在长文本方面存在问题)。你可以在这里找到我的示例项目:
https://github.com/jintoga/Dashed-Underlined-TextView/blob/master/Untitled.png。
public class DashedUnderlineSpan implements LineBackgroundSpan, LineHeightSpan {
private Paint paint;
private TextView textView;
private float offsetY;
private float spacingExtra;
public DashedUnderlineSpan(TextView textView, int color, float thickness, float dashPath,
float offsetY, float spacingExtra) {
this.paint = new Paint();
this.paint.setColor(color);
this.paint.setStyle(Paint.Style.STROKE);
this.paint.setPathEffect(new DashPathEffect(new float[] { dashPath, dashPath }, 0));
this.paint.setStrokeWidth(thickness);
this.textView = textView;
this.offsetY = offsetY;
this.spacingExtra = spacingExtra;
}
@Override
public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v,
Paint.FontMetricsInt fm) {
fm.ascent -= spacingExtra;
fm.top -= spacingExtra;
fm.descent += spacingExtra;
fm.bottom += spacingExtra;
}
@Override
public void drawBackground(Canvas canvas, Paint p, int left, int right, int top, int baseline,
int bottom, CharSequence text, int start, int end, int lnum) {
int lineNum = textView.getLineCount();
for (int i = 0; i < lineNum; i++) {
Layout layout = textView.getLayout();
canvas.drawLine(layout.getLineLeft(i), layout.getLineBottom(i) - spacingExtra + offsetY,
layout.getLineRight(i), layout.getLineBottom(i) - spacingExtra + offsetY,
this.paint);
}
}
}
结果:
![虚线下划线](https://istack.dev59.com/TIL6O.webp)
canvas.drawLine()
时存在已知的bug(已知问题),作为禁用硬件加速的替代方案,您可以使用canvas.drawPath
代替。 - hgoeblandroid:layerType="software"
。 - Jonik