Home » Android » Android: Color To Int conversion

Android: Color To Int conversion

Posted by: admin April 23, 2020 Leave a comment

Questions:

This might be a stupid question but I’m surprised that Paint class has no setColor(Color c) method. I want to do the following:

public void setColor(Color color) {
/* ... */
Paint p = new Paint();
p.setColor(color); // set color takes only int as a paramter :(
/* ... */
}

So any easy way to convert Color to int?

How to&Answers:

Any color parse into int simplest two way here:

1) Get System Color

int redColorValue = Color.RED;

2) Any Color Hex Code as a String Argument

int greenColorValue = Color.parseColor("#00ff00")

MUST REMEMBER in above code Color class must be android.graphics...!

Answer:

All the methods and variables in Color are static. You can not instantiate a Color object.

Official Color Docs

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.

The components are stored as follows (alpha << 24) | (red << 16) | (green << 8) | blue.

Each component ranges between 0..255 with 0 meaning no contribution for that component, and 255 meaning 100% contribution.

Thus opaque-black would be 0xFF000000 (100% opaque but no contributions from red, green, or blue), and opaque-white would be 0xFFFFFFFF

Answer:

R.color.black or some color are obviously integers. It needs a RGB value. You can give your own like #FF123454 which represents various primary colors

Answer:

Paint DOES have set color function.

/**
 * Set the paint's color. Note that the color is an int containing alpha
 * as well as r,g,b. This 32bit value is not premultiplied, meaning that
 * its alpha can be any value, regardless of the values of r,g,b.
 * See the Color class for more details.
 *
 * @param color The new color (including alpha) to set in the paint.
 */
public native void setColor(@ColorInt int color);

As an Android developer, I set paint color like this…

paint.setColor(getResources().getColor(R.color.xxx));

I define the color value on color.xml something like…

<color name="xxx">#008fd2</color>

By the way if you want to the hex RGB value of specific color value, then you can check website like this: http://www.rapidtables.com/web/color/RGB_Color.htm

I hope this helps ! Enjoy coding!

Answer:

I think it should be R.color.black

Also take a look at Converting android color string in runtime into int