在工作中,遇到这样一种需求,TextView 中有字体大小不一致的文字,要求顶部对齐。如下图
1557305193845.jpgpublic class TopAlignSpan extends SuperscriptSpan {
/** 字体大小 */
private float fontSizePx;
//shift value, 0 to 1.0
protected float shiftPercentage = 0;
//doesn't shift
public TopAlignSpan(float fontSizePx) {
this(fontSizePx, 0);
}
//sets the shift percentage
public TopAlignSpan(float fontSizePx, float shiftPercentage) {
if (shiftPercentage > 0.0 && shiftPercentage < 1.0) {
this.shiftPercentage = shiftPercentage;
}
this.fontSizePx = fontSizePx;
}
@Override
public void updateDrawState(TextPaint tp) {
//original ascent
float ascent = tp.ascent();
//scale down the font
tp.setTextSize(fontSizePx);
//get the new font ascent
float newAscent = tp.getFontMetrics().ascent;
//move baseline to top of old font, then move down size of new font
//adjust for errors with shift percentage
// tp.baselineShift += (ascent - ascent * shiftPercentage)
// - (newAscent - newAscent * shiftPercentage);
//计算基线偏移量
tp.baselineShift += (ascent - newAscent) * (1 - shiftPercentage);
}
@Override
public void updateMeasureState(TextPaint tp) {
updateDrawState(tp);
}
}
网友评论