Android scaledrawable doesn't seems to work

Just today I faced the same problem. The ScaleDrawable does not seem to work. After some investigation I've found the solution:

If you look at the documentation you can find this phrase: "A Drawable that changes the size of another Drawable based on its current level value." That's it.

It became clear after I found the onBoundsChange() function uses the strange level variable.

For you the code would be something like this:

Resources res = getResources();
ScaleDrawable sd = (ScaleDrawable) res.getDrawable(R.drawable.logo2);
Drawable d = sd.getDrawable();

d.setLevel(1);

ImageView iv = new ImageView(this);
iv.setImageDrawable(sd);
iv.setAdjustViewBounds(true); 
iv.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

setContentView(iv);

Update: I think the problem in the draw() function. Because after an initialization the level variable is 0:

public void draw(Canvas canvas) {
    if (mScaleState.mDrawable.getLevel() != 0)
        mScaleState.mDrawable.draw(canvas);
}

Update: Maybe then this code may help you:

private void useScaledImage() {
    Resources res = getResources();
    BitmapDrawable bd = (BitmapDrawable)res.getDrawable(R.drawable.sun);
    Bitmap b = Bitmap.createScaledBitmap(bd.getBitmap(),
                         (int) (bd.getIntrinsicHeight() * 0.7),
                         (int) (bd.getIntrinsicWidth() * 0.7),
                         false);

    LinearLayout l = new LinearLayout(this);
    ImageView iv = new ImageView(this);

    iv.setImageDrawable(new BitmapDrawable(b));
    iv.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

    l.addView(iv);

    setContentView(l);
}

Use inset drawable instead of scale drawable

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android" 
    android:drawable="@drawable/logo"
    android:insetTop="2dp"
    android:insetLeft="2dp"  
    android:insetRight="2dp"
    android:insetBottom="2dp"
    >

Tags:

Android