导航
导航

CenterVerticalTextSpan

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* 使TextView中不同大小字体垂直居中
* Created by Robin on 2018/11/8.
* Email: robinxdroid@gmail.com
* Blog: http://robinx.net/
*/
public class CenterVerticalTextSpan extends ReplacementSpan {
private int fontSizePx; //字体大小px

public CenterVerticalTextSpan(int fontSizePx) {
this.fontSizePx = fontSizePx;
}

@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
text = text.subSequence(start, end);
Paint p = getCustomTextPaint(paint);
return (int) p.measureText(text.toString());
}

@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
text = text.subSequence(start, end);
Paint p = getCustomTextPaint(paint);
Paint.FontMetricsInt fm = p.getFontMetricsInt();
canvas.drawText(text.toString(), x, y - ((y + fm.descent + y + fm.ascent) / 2 - (bottom + top) / 2), p); //此处重新计算y坐标,使字体居中
}

private TextPaint getCustomTextPaint(Paint srcPaint) {
TextPaint paint = new TextPaint(srcPaint);
paint.setTextSize(fontSizePx); //设定字体大小, sp转换为px
return paint;
}
}

转载请指明出处RobinBlog:http://robinx.net/2018/11/12/CenterVerticalTextSpan/