package com.bokecc.livemodule.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.style.ImageSpan;

/**
 * Copyright (C), 20105-2021, 创盛视联数码科技（北京）有限公司
 * FileName:
 * Author:
 * Date: 2023/1/11
 * Description:
 */
public class CenterImageSpan extends ImageSpan {


    public CenterImageSpan(@NonNull Context context, int resourceId) {
        super(context, resourceId);
    }


    @Override
    public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) {
        Drawable b = getDrawable();
        Rect rect = b.getBounds();

        if (fm!=null){
            Paint.FontMetricsInt fontMetricsInt = paint.getFontMetricsInt();
            int fontHeight = fontMetricsInt.bottom-fontMetricsInt.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(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
        Drawable b = getDrawable();
        canvas.save();

        int transY = 0;
        Paint.FontMetricsInt fm = paint.getFontMetricsInt();
        transY = (y + fm.descent + y + fm.ascent) / 2
                - b.getBounds().bottom / 2;

        canvas.translate(x, transY);
        b.draw(canvas);
        canvas.restore();
    }
}
