|
@@ -0,0 +1,63 @@
|
|
|
+package com.rui.common_base.widget.span;
|
|
|
+
|
|
|
+import android.content.Context;
|
|
|
+import android.graphics.Bitmap;
|
|
|
+import android.graphics.Canvas;
|
|
|
+import android.graphics.Paint;
|
|
|
+import android.graphics.Rect;
|
|
|
+import android.graphics.drawable.Drawable;
|
|
|
+import android.text.style.ImageSpan;
|
|
|
+
|
|
|
+import androidx.annotation.NonNull;
|
|
|
+
|
|
|
+/**
|
|
|
+ * Author by pq, Date on 2023/10/20.
|
|
|
+ */
|
|
|
+public class CenterImageSpan extends ImageSpan {
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 规定这个Span占几个字的宽度
|
|
|
+ */
|
|
|
+ private float mFontWidthMultiple = -1f;
|
|
|
+
|
|
|
+ public CenterImageSpan(@NonNull Drawable drawable, int verticalAlignment, int fontWidthMultiple) {
|
|
|
+ super(drawable, verticalAlignment);
|
|
|
+ this.mFontWidthMultiple = fontWidthMultiple;
|
|
|
+ }
|
|
|
+
|
|
|
+ public CenterImageSpan(@NonNull Context context, @NonNull Bitmap bitmap) {
|
|
|
+ super(context, bitmap);
|
|
|
+ }
|
|
|
+
|
|
|
+ @Override
|
|
|
+ public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
|
|
|
+ Drawable drawable = getDrawable();
|
|
|
+ Rect rect = drawable.getBounds();
|
|
|
+ if (fm != null) {
|
|
|
+ Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
|
|
|
+ int fontHeight = fmPaint.bottom - fmPaint.top;
|
|
|
+ int drHeight = rect.bottom - rect.top;
|
|
|
+ int centerY = fmPaint.top + fontHeight / 2;
|
|
|
+ fm.ascent = centerY - drHeight / 2;
|
|
|
+ fm.descent = centerY + drHeight / 2;
|
|
|
+ fm.top = fm.ascent;
|
|
|
+ fm.bottom = fm.descent;
|
|
|
+ }
|
|
|
+ int result = rect.right;
|
|
|
+ if (mFontWidthMultiple > 0) {
|
|
|
+ result = (int) (paint.measureText("子") * mFontWidthMultiple);
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ @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 + top;
|
|
|
+ canvas.translate(x, transY);
|
|
|
+ drawable.draw(canvas);
|
|
|
+ canvas.restore();
|
|
|
+ }
|
|
|
+}
|