public class DrawableCenterTextView extends TextView {
float textWidth;
float drawableWidth;
double textHight;
int drawableHeight;
int drawablePadding;
public DrawableCenterTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public DrawableCenterTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DrawableCenterTextView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable[] drawables = getCompoundDrawables();//left top right bottom
if (drawables != null) {
Drawable drawableLeft = drawables[0];
if (drawableLeft != null) {
textWidth = getPaint().measureText(getText().toString());
drawablePadding = getCompoundDrawablePadding();
drawableWidth = drawableLeft.getIntrinsicWidth();
float bodyWidth = textWidth + drawableWidth + drawablePadding;
canvas.translate((getWidth() - bodyWidth) / 2, 0);
setGravity(Gravity.CENTER_VERTICAL);
}
Drawable drawableTop = drawables[1];
if (drawableTop != null) {
textHight = Math.ceil(getPaint().descent() - getPaint().ascent());
drawablePadding = getCompoundDrawablePadding();
drawableHeight = drawableTop.getIntrinsicHeight();
float bodyHeight = (float) (textHight + drawableHeight + drawablePadding);
canvas.translate(0, (getHeight() - bodyHeight) / 2);
setGravity(Gravity.CENTER_HORIZONTAL);
}
}
super.onDraw(canvas);
}
}
自定义TextView,解决drawleft和drawtop,图片不居中的问题
最新推荐文章于 2021-09-14 09:31:38 发布