美文网首页工作生活
Android TextView 字体-顶部对齐

Android TextView 字体-顶部对齐

作者: 小程序猿一枚 | 来源:发表于2019-07-04 10:40 被阅读0次

    在工作中,遇到这样一种需求,TextView 中有字体大小不一致的文字,要求顶部对齐。如下图

    1557305193845.jpg
    public 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);
        }
    }
    

    相关文章

      网友评论

        本文标题:Android TextView 字体-顶部对齐

        本文链接:https://www.haomeiwen.com/subject/myklhctx.html