做论坛或者空间的时候会有表情之类的,但发现表情嵌入到TextView里面不居中对齐了。
有时候的需求是要居中对齐的,特别是表情这样的小图。
刚开始一直看textview的代码,看能不能做下手脚,单找了好久,没发现哪里可以改,最后想想了下,iamgeSpan中应该有做东西,就看了一下imagespan的代码,果然发现了如下方法
@Override
public int getSize(Paint paint, CharSequence text, int start, int end,
FontMetricsInt fm)
public void draw(Canvas canvas, CharSequence text, int start, int end,
float x, int top, int y, int bottom, Paint paint)
是不是可以解决了
@Override
public int getSize(Paint paint, CharSequence text, int start, int end,
FontMetricsInt fm) {
Drawable d = getDrawable();
Rect rect = d.getBounds();
if (fm != null) {
FontMetrics fontMetrics = paint.getFontMetrics();
int fontHeight = (int) (fontMetrics.bottom - fontMetrics.top);
int drHeight = rect.bottom - rect.top;
int top = drHeight / 2 - fontHeight / 4;
int bottom = drHeight / 2 + fontHeight / 4;
fm.ascent = -bottom;
fm.descent = top;
fm.top = -bottom;
fm.bottom = top;
}
return rect.right;
}
改变图片的baseline,draw方法就不用做什么了
是不是居中了。代码简单,重写下imagespan就可以了
不上代码了
来个全部的代码
private class MyImageSpan extends ImageSpan {
public MyImageSpan(Context context, int resourceId) {
super(context, resourceId);
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end,
FontMetricsInt fm) {
Drawable d = getDrawable();
Rect rect = d.getBounds();
if (fm != null) {
FontMetrics fontMetrics = paint.getFontMetrics();
int fontHeight = (int) (fontMetrics.bottom - fontMetrics.top);
int drHeight = rect.bottom - rect.top;
int top = drHeight / 2 - fontHeight / 4;
int bottom = drHeight / 2 + fontHeight / 4;
fm.ascent = -bottom;
fm.descent = top;
fm.top = -bottom;
fm.bottom = 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 drawable = getDrawable();
// canvas.save();
// int transY = 0;
// transY = ((bottom - top) - drawable.getBounds().bottom) / 2;
// canvas.translate(x, transY);
// drawable.draw(canvas);
// canvas.restore();
super.draw(canvas, text, start, end, x, top, y, bottom, paint);
}
}
对于内部类最好写成静态内部类。这是输入性能优化的了