【问题标题】:Aligning ImageSpan with Spanable String将 ImageSpan 与 Spanable 字符串对齐
【发布时间】:2017-07-07 10:23:59
【问题描述】:

我知道有很多相同类型的问题可用,我尝试了很多解决方案,但都没有满足我的要求。

我的问题是我必须在包含 Spanable 字符串和 Imagespan 的文本之间添加动态行距,但是当我添加行距时,文本和图像的对齐会失真。

我已经尝试了 Stackoverflow 上几乎所有可用的解决方案,例如 thisthisthis,但一切都顺理成章。 我附上了截图

  1. 添加动态行距之前的屏幕截图

2.添加动态行距后的截图

任何帮助将不胜感激。提前致谢!

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    在onDraw方法中使用“y”找到文本的基线,然后将drawable与文本视图的基线对齐

    public class VerticalImageSpan extends ImageSpan {
    
    
    
     public VerticalImageSpan(Drawable drawable) {
            super(drawable);
        }
    
        /**
         * update the text line height
         */
        @Override
        public int getSize(Paint paint, CharSequence text, int start, int end,
                           Paint.FontMetricsInt fontMetricsInt) {
            Drawable drawable = getDrawable();
            Rect rect = drawable.getBounds();
            if (fontMetricsInt != null) {
                Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
                int fontHeight = fmPaint.descent - fmPaint.ascent;
                int drHeight = rect.bottom - rect.top;
                int centerY = fmPaint.ascent + fontHeight / 2;
    
                fontMetricsInt.ascent = centerY - drHeight / 2;
                fontMetricsInt.top = fontMetricsInt.ascent;
                fontMetricsInt.bottom = centerY + drHeight / 2;
                fontMetricsInt.descent = fontMetricsInt.bottom;
            }
            return rect.right;
        }
    
        /**
         * see detail message in android.text.TextLine
         *
         * @param canvas the canvas, can be null if not rendering
         * @param text   the text to be draw
         * @param start  the text start position
         * @param end    the text end position
         * @param x      the edge of the replacement closest to the leading margin
         * @param top    the top of the line
         * @param y      the baseline
         * @param bottom the bottom of the line
         * @param paint  the work paint
         */
        @Override
        public void draw(Canvas canvas, CharSequence text, int start, int end,
                         float x, int top, int y, int bottom, Paint paint) {
    
            Drawable drawable = getDrawable();
            canvas.save();
            Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
            int fontHeight = fmPaint.descent - fmPaint.ascent;
            int centerY = y + fmPaint.descent - fontHeight / 2;
            int transY = centerY - (drawable.getBounds().bottom - drawable.getBounds().top) / 2;
            canvas.translate(x, transY);
            drawable.draw(canvas);
            canvas.restore();
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-21
      • 2017-04-20
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多