Color

Android colors are represented with four numbers, one each for alpha, red, green, and blue (ARGB). Each component can have 256 possible values, or 8 bits, so a color is typically packed into a 32-bit integer. For efficiency, Android code uses an integer instead of an instance of the Color class.

1. Functionality for four-dimensional graphics was considered for Android, but it was dropped because of a lack of time.

Red, green, and blue are self-explanatory, but alpha might not be. Alpha is a measure of transparency. The lowest value, 0, indicates the color is completely transparent. It doesn't really matter what the values for RGB are, if A is 0. The highest value, 255, indicates the color is completely opaque. Values in the middle are used for translucent, or semitransparent, colors. They let you see some of what is underneath the object being drawn in the foreground.

To create a color, you can use one of the static constants on the Color class, like this:

int color = Color.BLUE; // solid blue or if you know the alpha, red, green, and blue numbers, you can use one of the static factory methods such as the following:

// Translucent purple color = Color.argb(127, 255, 0, 255);

If possible, though, you're usually better off defining all your colors in an XML resource file. This lets you change them easily in one place later:

<?xml version="1.0" encoding="utf-8"?> <resources>

<color name="mycolor">#7fff00ff</color> </resources>

You can reference colors by name in other XML files, as we did in Chapter 3, or you can use them in Java code like this: color = getResourcesO.getColor(R.color.mycolor);

The getResources() method returns the ResourceManager class for the current activity, and getColor( ) asks the manager to look up a color given a resource ID.

0 0

Post a comment