After seeing many questions for this feature and attempting to follow the answers, I was left wondering if there was a clearer example to be had?
Edit: I was attempting
try this custom Drawable:
class BackgroundDrawable extends StateListDrawable {
private StateListDrawable mDrawable;
private Bitmap mBitmap;
private Matrix mMatrix;
private boolean mScale;
private int mGravity;
private int mDx;
private int mDy;
public BackgroundDrawable(StateListDrawable sld, Resources res, int resId, boolean scale, int gravity, int dx, int dy) {
mDrawable = sld;
mBitmap = BitmapFactory.decodeResource(res, resId);
mMatrix = new Matrix();
mScale = scale;
mGravity = gravity;
mDx = dx;
mDy = dy;
}
public static void setupBackground(View v, int resId, boolean scale, int gravity, int horizontalPadding, int verticalPadding) {
Drawable d = v.getBackground();
if (d instanceof StateListDrawable) {
StateListDrawable sld = (StateListDrawable) d;
Drawable drawable = new BackgroundDrawable(sld, v.getResources(), resId, scale, gravity, horizontalPadding, verticalPadding);
v.setBackgroundDrawable(drawable);
}
}
@Override
protected boolean onStateChange(int[] stateSet) {
invalidateSelf();
return super.onStateChange(stateSet);
}
@Override
protected void onBoundsChange(Rect bounds) {
mDrawable.setBounds(bounds);
Rect b = new Rect(bounds);
b.inset(mDx, mDy);
RectF src = new RectF(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
RectF dst = new RectF(b);
float[] values = new float[9];
if (mScale) {
mMatrix.setRectToRect(src, dst, ScaleToFit.START);
}
mMatrix.getValues(values);
float sx = values[Matrix.MSCALE_X];
float sy = values[Matrix.MSCALE_Y];
Rect outRect = new Rect();
Gravity.apply(mGravity, (int) (src.width() * sx), (int) (src.height() * sy), b, outRect);
mMatrix.postTranslate(outRect.left, outRect.top);
}
@Override
public void draw(Canvas canvas) {
int[] stateSet = getState();
mDrawable.setState(stateSet);
mDrawable.draw(canvas);
canvas.drawBitmap(mBitmap, mMatrix, null);
}
}
and how to use it:
Button b0 = (Button) findViewById(R.id.b0);
BackgroundDrawable.setupBackground(b0, R.drawable.ic_launcher, false, Gravity.BOTTOM | Gravity.RIGHT, 10, 5);
Button b1 = (Button) findViewById(R.id.b1);
BackgroundDrawable.setupBackground(b1, R.drawable.ic_launcher, false, Gravity.TOP, 0, 0);