3
我知道有很多相同類型的問題可用,我嘗試了很多解決方案,但都不符合我的要求。用Spanable String對齊ImageSpan
我的問題是,我必須添加包含Spanable字符串和Imagespan的文本之間的動態行間距,但是當我添加行距時,文本和圖像的對齊會變形。
我已經嘗試了幾乎所有的解決方案的提供#2像this,this & this但所有的靜脈。 我已附加截圖
我知道有很多相同類型的問題可用,我嘗試了很多解決方案,但都不符合我的要求。用Spanable String對齊ImageSpan
我的問題是,我必須添加包含Spanable字符串和Imagespan的文本之間的動態行間距,但是當我添加行距時,文本和圖像的對齊會變形。
我已經嘗試了幾乎所有的解決方案的提供#2像this,this & this但所有的靜脈。 我已附加截圖
使用的「y」的onDraw方法查找文本的基線,然後繪製對齊文本視圖的基線
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();
}
}