gpt4 book ai didi

android - 将 ImageSpan 与可生成字符串对齐

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:19:07 31 4
gpt4 key购买 nike

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

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

我已经尝试了 Stackoverflow 上几乎所有可用的解决方案,例如 this , this & this但一切都在静脉中。我附上截图

  1. 添加动态行间距前的截图

Screenshot before adding dynamic line spacing 2.添加动态行距后截图

Screenshot after adding dynamic line spacing

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

最佳答案

在 onDraw 方法中使用 "y"找到文本的基线,然后将可绘制对象与 TextView 的基线对齐

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();
}

}

关于android - 将 ImageSpan 与可生成字符串对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44968443/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com