How to change the opacity of an image.

I have a background image set to ImageView . Now I want to change the opacity of the image, because for this I am writing this code to change the opacity of the ImageView, but when I do this, it removes the background image from the image view. So my question is how to change the opacity of the ImageView without removing its background image.

Used code:

 ImageView imageView = (ImageView) findViewById(R.id.image_view); imageView.setBackgroundResource(R.drawable.theme1_page_header); // Set background image int opacity = 100; // from 0 to 255 imageView.setBackgroundColor(opacity * 0x1000000); // change opacity of image 
+8
source share
7 answers

the most important part of alpha is that the value must be decimal

0 = transparent and 1 = visible

so 0.5 is apparently half visible

in XML you can do

 <ImageView android:layout_width="30dp" android:layout_height="35dp" android:id="@+id/imageView" android:alpha="0.4" // <----------------- this is the fun part android:layout_alignParentRight="false" android:background="@drawable/imagename" android:layout_alignParentLeft="false" android:layout_alignParentTop="false" android:layout_alignWithParentIfMissing="false" android:layout_marginLeft="100dp" android:layout_alignParentBottom="false" android:layout_alignParentStart="false" android:layout_alignTop="@+id/bar" android:layout_marginTop="30dp"/> 
+27
source

You can use

 imageView.setAlpha(yourValue); // some value 0-255 where 0 is fully transparent and 255 is fully opaque 

See documentation

+11
source
 ImageView imageView = (ImageView) findViewById(R.id.image_view); Drawable dPage_header= getResources().getDrawable(R.drawable.theme1_page_header); // setting the opacity (alpha) dPage_header.setAlpha(10); // setting the images on the ImageViews imageView.setImageDrawable(dPage_header); 
+5
source

Use this option in the xml layout for opacity, and also to switch Android Material icons from black to gray. Android: alpha = 0.5

+1
source

With Api> = 16. Use setImageAlpha as your practice, because setAlpha will become obsolete in the future. `

ImageView.setAlpha(int) was renamed before ImageView.setImageAlpha(int) to avoid confusion. See detailed description here.

+1
source

Option 1

Use imageView.setAlpha(100) .

If you are using Android 2.3, you need to do a terrible hack with zero-length animation using 9-dimensional droids.

Option 2

Subclass ImageView and override its onDraw() method to make the image transparent.

Option 3

Actually change the pixels of an image using get/setPixel() . It will be very slow, though; perhaps there is a faster way to do this (for example, using renderscript).

0
source

In Kotlin, we can change the alpha in the code like this:

 myImageView.alpha = 0.5f 

Change the alpha value to any value from 0.0f to 1f

0
source

All Articles