55 lines
1.9 KiB
Java
55 lines
1.9 KiB
Java
package com.gh.common.view;
|
|
|
|
import android.content.Context;
|
|
import android.graphics.Canvas;
|
|
import android.graphics.Paint;
|
|
import android.graphics.Rect;
|
|
import android.graphics.drawable.Drawable;
|
|
import android.text.style.ImageSpan;
|
|
|
|
/**
|
|
* 图文中心对齐
|
|
*/
|
|
public class CenterImageSpan extends ImageSpan {
|
|
public CenterImageSpan(Context context, int resourceId) {
|
|
super(context, resourceId);
|
|
}
|
|
|
|
public CenterImageSpan(Drawable drawable) {
|
|
super(drawable);
|
|
}
|
|
|
|
@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 + 1; // fuck 这里不加 1px 会导致图片底部被截掉 1px
|
|
fontMetricsInt.descent = fontMetricsInt.bottom;
|
|
}
|
|
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();
|
|
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();
|
|
}
|
|
|
|
} |