Comic Sans MS Lover
Comic Sans MS Lover

Reputation: 1729

Android how to set opacity in bitmap xml

I need to create a bitmap resource via xml, like:

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/btn_home"
    >
</bitmap>

But I need to set opacity to this bitmap. Is there a way I can do this using this xml? I know that it would work if Shape tag was allowed inside of the bitmap tag, but I tried with no success.

Upvotes: 5

Views: 1759

Answers (1)

user1391869
user1391869

Reputation:

If you’re displaying the Bitmap in an ImageView, you can probably use the ImageView.setAlpha(int) method. However, if the ImageView is accesed via RemoteViews, as is the case when updating a widget, you won’t be able to invoke this method (if you try to call it via RemoteViews.setInt(int, String, int) you’ll get an exception telling you as much).

 private Bitmap adjustOpacity(Bitmap bitmap, int opacity)
    {
        Bitmap mutableBitmap = bitmap.isMutable()
                               ? bitmap
                               : bitmap.copy(Bitmap.Config.ARGB_8888, true);
        Canvas canvas = new Canvas(mutableBitmap);
        int colour = (opacity & 0xFF) << 24;
        canvas.drawColor(colour, PorterDuff.Mode.DST_IN);
        return mutableBitmap;
    }

More info. and most common just like you problem. How to Set Opacity (Alpha) for View in Android

Documentation of Bitmap from developer.android.com.

Upvotes: 3

Related Questions