我的解决方案现在来自一个按钮......它满足了我的所有要求......我不知道,如果文本的测量真的是那样精确,但它看起来是这样......如果不是,每个人得到背后的想法,可以调整......
谢谢你的帮助,虽然
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.widget.Button;
public class CenterImageTextButton extends Button {
private Paint mPaint = new Paint();
private String mText = null;
private float mTextSize = 0;
public CenterImageTextButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CenterImageTextButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CenterImageTextButton(Context context) {
super(context);
}
@Override
public void onDraw(Canvas canvas) {
mText = getText().toString();
mTextSize = getTextSize();
mPaint.setStyle(Style.FILL);
mPaint.setColor(getCurrentTextColor());
// get image top
Drawable drawable = getCompoundDrawables()[1];
Drawable curDrawable = null;
if (drawable instanceof StateListDrawable)
curDrawable = ((StateListDrawable)drawable).getCurrent();
else
curDrawable = ((BitmapDrawable)drawable).getCurrent();
Bitmap image = ((BitmapDrawable)curDrawable).getBitmap();
// call default drawing method without image/text
setText("");
setCompoundDrawables(null, null, null, null);
super.onDraw(canvas);
setText(mText);
setCompoundDrawables(null, drawable, null, null);
// get measurements of button and Image
int width = getMeasuredWidth();
int height = getMeasuredHeight();
int imgWidth = image.getWidth();
int imgHeight = image.getHeight();
// get measurements of text
//float densityMultiplier = getContext().getResources().getDisplayMetrics().density;
//float scaledPx = textSize * densityMultiplier;
//paint.setTextSize(scaledPx);
mPaint.setTextSize(mTextSize);
float textWidth = mPaint.measureText(mText);
// draw Image and text
float groupHeight = imgHeight + mTextSize;
canvas.drawBitmap(image, (width - imgWidth) / 2, (height - groupHeight) / 2, null);
canvas.drawText(mText, (width - textWidth) / 2, mTextSize + (height - groupHeight) / 2 + imgHeight, mPaint);
}
}