Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change int color opacity in java/android

I am trying to change the opacity of a color that I get of my theme with the next code:

TypedValue typedValueDrawerSelected = new TypedValue();
getTheme().resolveAttribute(R.attr.colorPrimary, typedValueDrawerSelected, true);
int colorDrawerItemSelected = typedValueDrawerSelected.data;

I want that the colorDrawerItemSelected keeps the same color, buth its alpha should be 25%.

I found some solutions getting the rgb color from the imageView, but I havent imageView.

Thank you for your time.

like image 350
JavierSegoviaCordoba Avatar asked Feb 12 '15 17:02

JavierSegoviaCordoba


People also ask

How to set color opacity in android?

setAlpha(51); Here you can set the opacity between 0 (fully transparent) to 255 (completely opaque). The 51 is exactly the 20% you want.

How do I reduce opacity on my Android?

Use imageView. setAlpha(100) .

What is color in android?

android.graphics.Color. The Color class provides methods for creating, converting and manipulating colors. Colors have three different representations: Color ints, the most common representation. Color longs.

What is a color int?

The Color class defines methods for creating and converting color ints. Colors are represented as packed ints, made up of 4 bytes: alpha, red, green, blue. The values are unpremultiplied, meaning any transparency is stored solely in the alpha component, and not in the color components.


2 Answers

Wouldn't it be sufficient?

colorDrawerItemSelected = (colorDrawerItemSelected & 0x00FFFFFF) | 0x40000000;

It saves the color value and sets the alpha to 25% of max.

First byte in the color int is responsible for the transparency: 0 - completely transparent, 255 (0xFF) – opaque. In the first part ("&" operation) we set the first byte to 0 and left other bytes untouched. In the second part we set the first byte to 0x40 which is the 25% of 0xFF (255 / 4 ≈ 64).

like image 50
Sergey Glotov Avatar answered Sep 28 '22 12:09

Sergey Glotov


I use this approach in my app:

private int getTransparentColor(int color){
    int alpha = Color.alpha(color);
    int red = Color.red(color);
    int green = Color.green(color);
    int blue = Color.blue(color);

    // Set alpha based on your logic, here I'm making it 25% of it's initial value. 
    alpha *= 0.25;

    return Color.argb(alpha, red, green, blue);
}

You can also use ColorUtils.alphaComponent(color, alpha) from the support lib.

like image 25
Rahul Sainani Avatar answered Sep 28 '22 10:09

Rahul Sainani