Reputation: 9650
In my android layout I am setting the background image so that it has a faded look (alpha) by referring to another xml like this:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/contraintLayout1"
...
android:background="@drawable/bg_fade"
bg_fade.xml
then defined like this:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/background"
android:alpha="0.3"/>
where background
is my actual jpg image in my drawables
folder.
This works fine, and I get the faded look I want.
Now I need to change the actual background image depending on the user preference. I know I can do this in code for setting a new like this:
contraintLayout1.setBackgroundResource(R.drawable.new_background)
But then I no longer have the faded look, just the "raw" image.
So I somehow need to change the src value in the bg_fade.xml file. But I don't know how I can do this in code.
Can somebody please help? (PS. I am coding in Kotlin)
Upvotes: 0
Views: 355
Reputation: 111
you can first define a method for change transparency of images like this
public Bitmap changeTransparency(int src, int value) {
Bitmap bMap = BitmapFactory.decodeResource(getResources(),src);
int width = bMap.getWidth();
int height = bMap.getHeight();
Bitmap transBMap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(transBMap);
canvas.drawARGB(0, 0, 0, 0);
final Paint paint = new Paint();
paint.setAlpha(value);
canvas.drawBitmap(bMap, 0, 0, paint);
return transBMap;
}
and then set the returned value to your view's background like this code
view.setBackgroundImage(changeTransparency(R.drawable.new_nackground, ALPHA_VALUE));
i hope be helpful
Upvotes: 1