今天給大家分析下,騰訊IM提供的Demo中表情和文本信息不管是在TextView還是EditText中不能對齊的問題
首先可以肯定騰訊IM中使用的是把assets下的一個文件夾中的圖片循環遍歷成一個BitMap;然後轉換成一個ImageSpan,最後放到SpannableStringBuilder裏面;
其實對齊方式的主要關鍵點在轉換ImageSpan的步驟裏;
如果從寫ImageeSpan的draw和getSize方法就可以將對不齊的問題解決;
下面就直接貼代碼吧
public class MyImageSpan extends ImageSpan { public MyImageSpan(Context context, Bitmap b, int verticalAlignment) { super(context, b, verticalAlignment); } public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) { Drawable d = getDrawable(); Rect rect = d.getBounds(); if (fm != null) { Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt(); int fontHeight = fmPaint.bottom - fmPaint.top; int drHeight = rect.bottom - rect.top; int top = drHeight / 2 - fontHeight / 4; int bottom = drHeight / 2 + fontHeight / 4; fm.ascent = -bottom; fm.top = -bottom; fm.bottom = top; fm.descent = top; } return rect.right; } @Override public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { Drawable b = getDrawable(); canvas.save(); int transY = 0; transY = ((bottom - top) - b.getBounds().bottom) / 2 + top; canvas.translate(x, transY); b.draw(canvas); canvas.restore(); } }
從寫構造方法是爲了和騰訊提供的Demo保持一致,希望對需要的小夥伴有所幫助