概述
都知道应用 SpannableString 实现TextView各种相关效果,这里遇到一种需求就是需要TextView部分文字大小不同,且居中显示。而使用SpannableString的默认效果是底部对齐,在这里就需要自定义。
效果图
默认.JPG居中对齐.JPG
代码
默认效果的实现代码
SpannableString spanStr = new SpannableString("后面的文字默认下部对齐");
spanStr.setSpan(new ForegroundColorSpan(Color.parseColor("#0000ff")), 0, 5, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
spanStr.setSpan(new RelativeSizeSpan(0.6f), 5, spanStr.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
textView.setText(spanStr);
居中显示的代码实现
private void initVIew() {
SpannableString spanStr1 = new SpannableString("后面的文字居中显示");
spanStr1.setSpan(new ForegroundColorSpan(Color.parseColor("#0000ff")), 0, 5, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
int fontSizePx1 = (int)sp2px(this, 12);
spanStr1.setSpan(new VerticalCenterSpan(fontSizePx1), 5, spanStr1.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
textView1.setText(spannableString1);
}
public static float sp2px(Context context, float sp) {
float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
return sp * scaledDensity;
}
/**
* 使TextView中不同大小字体垂直居中
*/
public class VerticalCenterSpan extends ReplacementSpan {
private float fontSizePx; //px
public VerticalCenterSpan(float 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();
// 此处重新计算y坐标,使字体居中
canvas.drawText(text.toString(), x, y - ((y + fm.descent + y + fm.ascent) / 2 - (bottom + top) / 2), p);
}
private TextPaint getCustomTextPaint(Paint srcPaint) {
TextPaint paint = new TextPaint(srcPaint);
paint.setTextSize(fontSizePx); //设定字体大小, sp转换为px
return paint;
}
}
补充
关于 SpannableString 实现TextView各种效果网上介绍比较多,这里给出一个标记一个比较详细的一个地址,仅供参考:
用SpannableString打造绚丽多彩的文本显示效果:https://www.jianshu.com/p/84067ad289d2
居中显示参考:
https://stackoverflow.com/questions/25628258/align-text-around-imagespan-center-vertical
https://blog.csdn.net/anroidyanyou/article/details/72466218
网友评论