android 字符串对齐,android – 使用Spanable String对齐ImageSpan
我知道有很多相同類型的問題可供使用,我嘗試了很多解決方案,但所有這些問題都達不到我的要求.
我的問題是我必須在包含Spanable字符串和Imagespan的文本之間添加動態行間距,但是當我添加行間距時,文本和圖像的對齊會變形.
我已經嘗試了Stackoverflow上幾乎所有可用的解決方案,如this,this& this但是一切都在靜脈中.
我附上了截圖
>添加動態行間距之前的屏幕截圖
2.添加動態行間距后的屏幕截圖
任何幫助將受到高度贊賞.提前致謝!
解決方法:
在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();
}
}
標簽:android,android-layout
來源: https://codeday.me/bug/20190701/1349634.html
總結
以上是生活随笔為你收集整理的android 字符串对齐,android – 使用Spanable String对齐ImageSpan的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 啊哈c语言推箱子小游戏,啊哈C入门版学完
- 下一篇: android recyclerview
