这个是我最终的图文居中span,如下:
public class CustomSpan extends ImageSpan { //图片适应文本行高度 int resourceId; int textColor; float textRadio; int marginH;//左右间隔 Rect rect; Drawable drawable; publicCustomSpan(Context context, int resourceId, int textColor, float textRadio, int marginH) { super(context,resourceId); this.resourceId= resourceId; drawable= context.getResources().getDrawable(resourceId); this.textRadio= textRadio; this.textColor= textColor; this.marginH= marginH; } @Override public int getSize(Paint paint,CharSequence text, intstart, intend,Paint.FontMetricsInt fm) { //设置图片块的宽度 CharSequence targetText=text.subSequence(start,end); Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt(); int txtW = (int) Math.ceil(paint.measureText(targetText.toString())); int fontHeight = fmPaint.descent- fmPaint.ascent; rect=newRect(0,0,txtW,fontHeight); return rect.right+2*marginH; } /** * see detail message in android.text.TextLine * *@paramcanvasthe canvas, can be null if not rendering *@paramtextthe text to be draw *@paramstartthe text start position *@paramendthe text end position *@paramxthe edge of the replacement closest to the leading margin *@paramtopthe top of the line //文本所在改行的顶部 *@paramythe baseline //文本的基准线 *@parambottomthe bottom of the line //文本所在改行的底部 及下行的顶部,xml文件中的设置的行间距 会直接影响 bottom到baseline的距离 *@parampaintthe work paint */ @Override public void draw(Canvas canvas,CharSequence text, int start, int end, float x, int top, int y, int bottom,Paint paint) { CharSequence targetText=text.subSequence(start,end); intoldTextColor =paint.getColor(); floatoldTextSize =paint.getTextSize(); // canvas.drawLine(0,top,400,top,paint); // canvas.drawLine(0,y,400,y,paint); // canvas.drawLine(0,bottom,400,bottom,paint); Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt(); int oldfontascent = fmPaint.ascent; paint.setColor(textColor); paint.setTextSize(oldTextSize*textRadio); fmPaint = paint.getFontMetricsInt(); int txtW = (int) Math.ceil(paint.measureText(targetText.toString())); int fontHeight = fmPaint.descent- fmPaint.ascent; canvas.save(); canvas.translate(marginH+x,y+oldfontascent);//移动到该块的原点 drawable.setBounds(rect);//背景的绘制 drawable.draw(canvas); Log.e("尺寸",rect.bottom-((rect.bottom-fontHeight))+","+(0-oldfontascent*textRadio)); canvas.translate((rect.right-txtW)/2.0f,rect.bottom/2.f+fontHeight/2-fmPaint.descent); //移动的值是相对的。移动到“块”中字体“服务中”baseline canvas.drawText(targetText.toString(),0,0,paint); paint.setColor(oldTextColor); paint.setTextSize(oldTextSize); canvas.restore(); } }