DrawableTextView.java
1.63 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
package com.sw.laryngoscope.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.TextView;
import androidx.annotation.Nullable;
@SuppressLint("AppCompatCustomView")
public class DrawableTextView extends TextView {
public DrawableTextView(Context context) {
super(context);
}
public DrawableTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public DrawableTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
// getCompoundDrawables() : Returns drawables for the left, top, right, and bottom borders.
Drawable[] drawable = getCompoundDrawables();
//得到drawableLeft设置的drawable对象
Drawable leftDrawable = drawable[0];
if (leftDrawable != null) {
//得到leftdrawable 的宽度
int leftDrawableWidth = leftDrawable.getIntrinsicWidth();
//得到drawable与text之间的间距
int drawablePadding = getCompoundDrawablePadding();
//得到文本的宽度
int textWidth = (int) getPaint().measureText(getText().toString().trim());
int bodyWidth = leftDrawableWidth + drawablePadding + textWidth;
canvas.save();
//将内容在X轴方向平移
canvas.translate((getWidth() - bodyWidth) / 2, 0);
}
super.onDraw(canvas);
}
}