CenterRadioButton.java
2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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);
}
}