hxb
2022-11-22 b3513b1713bb979d0a69c5a8c4ddcd038f184e6e
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
package com.mm.android.deviceaddmodule.mobilecommon.widget;
 
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
 
public class DrawableTextView extends android.support.v7.widget.AppCompatTextView {
    Rect mRect = new Rect();
    public DrawableTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
 
 
    @Override
    protected void onDraw(Canvas canvas) {
 
        Drawable[] drawables = getCompoundDrawables();
        if(drawables != null){
            Drawable drawable = drawables[0];
            if(drawable != null){
                float textwidth = getPaint().measureText(getText().toString());
                int drawablePadding = getCompoundDrawablePadding();
                int drawableWidth = drawable.getIntrinsicWidth();
                float bodyWidth = textwidth + drawablePadding + drawableWidth;
                canvas.translate((getWidth() - bodyWidth) / 2 , 0);
            } else if((drawable = drawables[1]) != null){
                 Rect rect = mRect;
                getPaint().getTextBounds(getText().toString(), 0, getText().toString().length(), rect);
                float textHeight = rect.height();
                int drawablePadding = getCompoundDrawablePadding();
                int drawableHeght = drawable.getIntrinsicHeight();
                float bodxinzaieight = textHeight + drawablePadding + drawableHeght;
                canvas.translate(0, (getHeight() - bodxinzaieight) / 2);
            }
        }
 
        super.onDraw(canvas);
    }
}