CenterRadioButton.java 2.07 KB
package com.sw.laryngoscope.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.RadioGroup;

import com.sw.laryngoscope.R;

public class CenterRadioButton extends androidx.appcompat.widget.AppCompatRadioButton {

    public CenterRadioButton(Context context) {
        this(context, null);
    }

    public CenterRadioButton(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.radioButtonStyle);
    }

    public CenterRadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Drawable[] drawables = getCompoundDrawables();
        if (drawables != null) {
            Drawable drawableTop = drawables[1];
            if (drawableTop != null) {
                float textHeight = measureHeight(getText().toString());
                int drawablePadding = getCompoundDrawablePadding();
                int drawableHeight = drawableTop.getIntrinsicHeight();
                //float bodyHeight = textHeight + drawableHeight + drawablePadding;
                //setPadding(0, (int)(getHeight() - bodyHeight), 0, 0);
                //canvas.translate(0, 0 - (getHeight() - bodyHeight) / 2);


                float bodyHeight = textHeight + drawableHeight + drawablePadding;
                setPadding(0, (int)(getHeight() - drawableHeight), 0, 0);
                canvas.translate(0, 0 - (getHeight() - drawableHeight) / 2);
            }
        }
        super.onDraw(canvas);
    }

    //获取文本高度
    public int measureHeight(String text) {
//        Rect result = new Rect();
//        // Measure the text rectangle to get the height
//        getPaint().getTextBounds(text, 0, text.length(), result);
//        return  result.height();
        Paint.FontMetrics fontMetrics = getPaint().getFontMetrics();

        return (int)(fontMetrics.descent - fontMetrics.ascent + fontMetrics.leading);
    }

}