Color in android a tutorial

what is Light ?

A light is a wave which doesn’t need a medium to propagate . Other examples of waves are water waves , or air waves which need water and air as a medium to propagate .Water , air and sound waves are known as mechanical waves . A wave has the following properties

  • it has a crest , which is the largest amplitude that this wave can have
  • it has a direction of propagation
  • it has a length , which is the distance between any two identical points on a wave , for example the distance between two crests .
  • it has a period which is time required for an identical point to repeat itself , so for example the time required for the crest at point A to reach point B .
  • a wave has a frequency , the frequency is 1 over the period . The period represents the amount it takes for a crest to repeat itself . the frequency is 1 over this this period , so it is the number of crest that passes through a point in one second.

Light is an electro magnetic wave , as such it has an electric field , and a magnetic field .

A magnetic field is for example the field that is generated by a magnet . This field can exert a force on certain materials , and attract them.

An electric field is created by attraction and repulsion of electrical charges . An electric charge is a property of matter that causes object to attract or to repel . An example of an electric field is when a ballon is rubbed on hair , the balloon will be charged negatively , and it will attract the hair .

A charged particle produces an electric field , and exerts a force on other charged particles. Charges that have the same sign attracts , and charges that have opposite signs repels . Positively charged particles accelerate in the same direction of the electrical field , and negatively charged particles accelerate in the inverse direction of the electric field .

A magnetic field is produced by moving charged particle , it exerts a force that is perpendicular to the speed of particles , as such it affects the direction of the particles , and not their speed .

A light wave is formed of charged particles . The particles in a light wave are called photon ,these particles create the wave . A light wave has energy , the energy of light wave is related to its frequency as such it is inversely proportional to its length. The higher the frequency , the shorter the wavelength , the higher the energy that a light wave has . The lower the frequency , the longer the wavelength , and the lower the energy that a light wave has .

The range of frequencies and energies of electro magnetic waves is know as the electromagnetic spectrum .The electro magnetic spectrum is classified in :

  • radio waves , have a length that is larger than 1* 10^-1 m
    • radio waves are used for radio , television .
  • micro waves have a length between and 1*10^-4 m and 1* 10^-1m
    • they are used for micro wave oven , and for radar .
  • infrared has a length between 7* 10^-7 m and 1 * 10^-4 m
    • warm bodies release infra red wave length . Infra red waves have a length that is below the length of a red wave which is a wave that we can see . Heat cameras and night vision cameras , use infra red waves .
  • visible lights has a length between 4 * 10^-7 m and 7 * 10^-7 m . These are waves that we can see . The longest one is the red wave , it has a wavelength of around 700 nm , and the shorted one is the violet it has a wavelength of around 380 nm .
  • ultra violet waves has a length between 1*10^-8 m and 4 * 10^-7 m
    • ultra violet waves are used for example in treatment of cancer.
  • x-rays has a wave length between 1 * 10^-9 m and 1 * 10^-8 m
    • x-rays waves can be used to check if a bone is broken
  • gamma rays has a wave length that is shorter than 1*10^-9 m
    • gamma rays can cause cancer , and they can be used to treat cancer and kill bacteria .

What is a color

 

Light is an electro magnetic wave , it has a length . We can classify light based on its wavelength . Visible light has a wavelength between 4 * 10^-7 m and 7 * 10^-7 m . Visible light can be seen by the human eye . The length of the wave specify the color that this wave has . The longest wave length that we can see is the red wave length , and the shortest wave length that we can see is the violet .

 

When all the visible light waves are seen together , we have the white lite . When light hits an object it is either reflected or absorbed . Our eyes absorb the reflected light waves from the object , and we are able to distinguish the colors of a light wave. The black color is the result of an object absorbing all light , or the absence of light

What is a color space or model?

we need a way to represent a color in the computer , so we have what is called the color space or model , which is the model by which we are representing a color in the computer , and creating colors in analog and digital devices .

In a color space or a color model , we have some basic colors from which all other colors are created ,

For example , if our basic colors are the red green and blue , then this color space is the red green blue color space , and it has the basic colors : red , green and blue . All other colors are created by combining these colors . So if you want the red green blue colors form the basis of a 3d coordinate system , where other colors are created by combining the value of these colors together .

Colors in android (32bits , 64bits , Color class)

colors in android are represented through either an int literal or a long literal or as an instance of the Color class , which creates a color represented as an int literal or a long literal . The Color class also has static methods that allow us to create int and long colors literals , and to convert between the different color space .

The int color literal has 32 bits , and it allow us to create only rgb colors where each components has 8 bits . The long color literal has 64 bits and it allow us to create colors that belong to different color space such as XYZ , RGB. The color long was added as of android O or version 8 , as such it is only available for api level 26 and higher .

Creating a 32 bits int rgb color in android

we can create a color in android by using only 32 bits , in this case the color belong to the RGB color space .

  • 8 bits are used to represent the alpha.
    • alpha is the transparency of the color
    • when the value of alpha is at its full , the color is fully opaque
    • when the value of alpha is at its lowest , the color is transparent
  • 8 bits are used to represent the red color
  • 8 bits are used to represent the green color
  • 8 bits are used to represent the blue color

 

 

each color and alpha channel takes 8 bit of storage , as such it takes a byte. A byte can have a value between 0 and 255 in decimal inclusive , or it can have a value between 0x00 and 0xFF in hexadecimal .

creating a 32 bits color using an int literal

we can create a color by using an integer literal which is specified in hex , this can be done in code or in xml . The format of the integer literal is

0xAARRGGBB

0x means that we are using hexadecimal to specify the colors . Two hexadecimal digits for each color and alpha are used

  • The first byte or two hex digits specify the alpha opacity , when it is 0xFF it is fully opaque , when it is 0x00 it is fully transparent .
  • The second byte or two hex digits are used to specify the red color
  • the third byte or two hex digits are used to specify the green color
  • the last byte or two hex digits are used to specify the blue color

in code

public @ColorInt static final int color = 0x00000000;

when creating color using code , we can declare its type as an int , and we must specify the color using a hexadecimal integer literal . The annotation @ColorInt that is used , is optional , and it is just used to annotate that this int is a color .

In this example , we have created an activity called ColorActivity which has a layout called activity_color.xml .

ColorActivity.java

package com.twiserandom.whatisacolor;

import android.graphics.Color;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

public class ColorActivity extends AppCompatActivity {

    ImageView srgbIv_RED , srgbIv_RED_HALF_ALPHA;
    /*
        @ColorInt
            just used to annotate that this color
            not necessary to use
     */
    public @ColorInt static final int  RED = 0xFFFF0000;
    public @ColorInt static final int  RED_HALF_ALPHA = 0x7FFF0000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_color);
        srgbIv_RED = (ImageView) findViewById(R.id.srgbIv_RED);
        srgbIv_RED_HALF_ALPHA = (ImageView) findViewById(R.id.srgbIv_RED_HALF_ALPHA);
        srgbIv_RED.setBackgroundColor(ColorActivity.RED);
        srgbIv_RED_HALF_ALPHA.setBackgroundColor(ColorActivity.RED_HALF_ALPHA);
        
    }

}


activity_color.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:id="@+id/srgbIv_RED"
        />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:id="@+id/srgbIv_RED_HALF_ALPHA"
        />
</LinearLayout>

The activity_color.xml contains a linear layout which has two image views . In the ColorActivity , we get the references for the views and we we set the background to the colors that we have defined .

 

in xml

to create a color using xml , we must use the colors.xml file located inside the values folder.

This file contains some predefined colors such as the colorPrimary , colorPrimaryDark , colorAccent .

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>
</resources>

we can define a new color by using a name and a value in the colors.xml file

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>
    <color name="green">#FF00FF00</color>
    <color name="green_half_alpha">#7F00FF00</color>
</resources>

So in this example we have defined a green color , and a green_half_alfa color . Our activity is called ColorActivity.java , which contains the following code

package com.twiserandom.whatisacolor;


import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

public class ColorActivity extends AppCompatActivity {

    ImageView srgbIv_GREEN , srgbIv_GREEN_HALF_ALPHA;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_color);
        srgbIv_GREEN = (ImageView) findViewById(R.id.srgbIv_GREEN);
        srgbIv_GREEN_HALF_ALPHA = (ImageView) findViewById(R.id.srgbIv_GREEN_HALF_ALPHA);
        srgbIv_GREEN.setBackgroundColor(ContextCompat.getColor(this, R.color.green));
        srgbIv_GREEN_HALF_ALPHA.setBackgroundColor(ContextCompat.getColor(this, R.color.green_half_alpha));

    }

}

and it has a layout file called activity_color.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:id="@+id/srgbIv_GREEN"
        />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:id="@+id/srgbIv_GREEN_HALF_ALPHA"
        />
</LinearLayout>

in the ColorActivity class we get the reference to the image views , and we set their background color to the color that we have defined. We use the ContextCompat.getColor method , passing to it the context of our activity which is the this keyword , and the name of the color by using R.color.colorname .

 

create a 32 bits int color using the Color class static methods

/*
create a color by specifying the components
alpha , red , green , blue
*/
public static int argb( int alpha, int red, int green, int blue)
public static int argb(float alpha, float red, float green, float blue)

/*
create a color by specifying the components 
red , green , blue
the alpha component is by default 255 or 1 
*/
public static int rgb( int alpha, int red, int green, int blue)
public static int rgb(float red, float green, float blue)

we can create a 32 bits int color by using the argb method , where we specify the color component as either a float or an int . The int value can be between 0 and 255 or 0x00 , and 0xFF , and the float value can be between 0 and 1 .

The float value of the argb method , is the int value divided by 255 . So when it is 1 it means we have specified a color component which has an int value of 255 , and when it is 0 it is as if we have defined a color which has an int value of 0.

In this example we have the ColorActivity class that has an activity_color.xml file . In the ColorActivity we get the reference for two image views , ad we set the background color using the greenColor and greenColorHalfAlpha variable .The variables have a color int value which was created using the static Color class methods .

package com.twiserandom.whatisacolor;

import android.graphics.Color;
import android.support.annotation.ColorInt;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

public class ColorActivity extends AppCompatActivity {
    ImageView srgbIv_GREEN , srgbIv_GREEN_HALF_ALPHA;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_color);
        srgbIv_GREEN = (ImageView) findViewById(R.id.srgbIv_GREEN);
        srgbIv_GREEN_HALF_ALPHA = (ImageView) findViewById(R.id.srgbIv_GREEN_HALF_ALPHA);
        //create a green color using the rgb static method
        @ColorInt int greenColor = Color.rgb(0,255,0);
        //create a green color using the argb static method  specifying the alpha to be 127 or half transparent
        @ColorInt int greenColorHalfAlpha = Color.argb(127,0,0,0);
        /* set the background colors of the image views*/
        srgbIv_GREEN.setBackgroundColor(greenColor);
        srgbIv_GREEN_HALF_ALPHA.setBackgroundColor(ContextCompat.getColor(this, R.color.green_half_alpha));

    }

}

activity_color.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:id="@+id/srgbIv_GREEN"
        />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:id="@+id/srgbIv_GREEN_HALF_ALPHA"
        />
</LinearLayout>

Creating a 64 bits long rgb color in android

the color space that can be represented by using a 64 bits long literal in android are :

  • rgb (srgb) : 8 bits per color (24 bits) , 8 bits for the alpha channel . (32 bits)
  • rgb : 16 bits per color (48 bits), 10 bits for alpha , 6 bits for the color space . (64 bits)
  • xyz : 16 bits per color (48 bits), 10 bits for alpha , 6 bits for the color space . (64 bits)
  • xyz labs : 16 bits per color (48 bits) , 10 bits for alpha , 6 bits for the color space .(64 bits)

the most used color space is the rgb color , when it uses only 32 bits it is known as srgb . We can create it either by using 32 bits , or we can create it by using 64 bits , in this case the last 32 bits are set to zero .

 

other colors can be created using the long color representation , in this case we must specify , the color components , the alfa component , and the other color space.

 

  • the first 48 bits are used to specify the colors component.
    • each 16 bits in the first 48 bits is used to specify the color component that belong to the color space that is specified
  • the ten next bits are used to specify the alfa component
  • the last 6 bits are used to specify the color space

since it is a little bit complex to create a 64 bit color by using a long literal , we can use the static methods of the Color class to create a 64 bits color .

create a 64 bits long color using the Color class static methods

there are many methods in the Color class that allows us to create a 64 bits long color. A 64 bits color in android can only be create for api level 26 or higher , so for android O or version 8.

We cannot use a long color by views in android , so we must convert it to a color int before usage .

pack(int)->long

public static long pack(@ColorInt int color)

will create an srgb long color , the last 32 bits will be filled with 0 , and the first 32 bits will be the SRGB color .

/*ColorActivity.java*/

package com.twiserandom.whatisacolor;



import android.graphics.Color;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorLong;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

public class ColorActivity extends AppCompatActivity {
    ImageView ivColor;

    @RequiresApi(api = Build.VERSION_CODES.O) /*Long Color can only be used for android version O or higher */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_color);

        /*Get the reference for the color imageViews*/
        ivColor = (ImageView) findViewById(R.id.ivColor);

        /*create a long color */
        @ColorLong Long aLongColor = Color.pack(0xFFFF0000);

        /*Convert long color to int*/
        /*Long color cannot be used with android view*/
        @ColorInt int anIntColor = Color.toArgb(aLongColor);
        ivColor.setBackgroundColor(anIntColor);



    }

}

/*activity_color.xml*/

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/ivColor"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />


</LinearLayout>

in this example we have an image view . We get the reference to the image view . we create a 64 bit srgb color , and later convert it to a 32 bit rgb color in order for it to be used by the image view as its background color .

 

pack(float red , float green , float blue )->long

public static long pack(float red, float green, float blue)
  • will create a 64 bit SRGB color from the red green and blue component.
  • The red , green and blue components are specified as a float between 0 and 1 .
  • The created color is srgb
    • it uses the first 32 bits of the 64 bits long
    • the last 32 bits are filled with zero.
    • each color will have an 8 bits
    • the alfa channel will have bits , which will be 0xFF by default .
/*ColorActivity.java*/
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorLong;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

public class ColorActivity extends AppCompatActivity {
    ImageView ivColor;

    @RequiresApi(api = Build.VERSION_CODES.O) /*Long Color can only be used for android version O or higher */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_color);

        /*Get the reference for the color imageViews*/
        ivColor = (ImageView) findViewById(R.id.ivColor);

        /*create a long color */
        @ColorLong Long aLongColor = Color.pack(0,1,0);

        /*Convert long color to int*/
        /*Long color cannot be used with android view*/
        @ColorInt int anIntColor = Color.toArgb(aLongColor);
        ivColor.setBackgroundColor(anIntColor);



    }

}


/*activity_color.xml*
/

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/ivColor"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />


</LinearLayout>

so in this example we have an imageView. We set its background color to green . We created the green color by using the pack methods which takes 3 values that represents red , green , blue. The alpha component has a default value of 1f .

An SRGB color uses only the first 32 bits , the last 32 bits of the long are set tozero . We can use the static method toArgb to convert a color from 64 bits to 32 bits .

pack(float red , float green, float blue , float alpha)->long

this method is similar to the pack(red, green , blue) method , but it takes an additional alpha component to create an SRGB color . It is used the same way as the pack(red,green,blue) method , we just have to specify an additional alpha component .

public static long pack(float red, float green, float blue, float alpha)

pack(float red, float green , float blue, float alpha , ColorSpace colorspace)->long

  • we can use this method to create a color either using a srgb colorspace , or rgb color space .
  • in Srgb color space each color takes 8 bits
  • in rgb each color takes 16 bits .
  • in the case of srgb
    • red , green and blue are [0-255]/255
    • alfa is [0-255]/255
  • in the case of rgb
    • red , green and blue are [0-65535]/65535
    • alfa is [0-1023]/1023
  • Color space is specified by using ColorSPace static properties
public static long pack(float red, float green, float blue, float alpha, ColorSpace colorSpace)

 

/*ColorActivity.java*/
public class ColorActivity extends AppCompatActivity {
    ImageView ivColor;

    @RequiresApi(api = Build.VERSION_CODES.O) /*Long Color can only be used for android version O or higher */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_color);

        /*Get the reference for the color imageViews*/
        ivColor = (ImageView) findViewById(R.id.ivColor);

        /*get srgb colorspace*/
        ColorSpace srgb = ColorSpace.get(ColorSpace.Named.SRGB);

        /*create a long color */
        @ColorLong Long aLongColor = Color.pack(1,1,0 , 1 , srgb);

        /*Convert long color to int*/
        /*Long color cannot be used with android view*/
        @ColorInt int anIntColor = Color.toArgb(aLongColor);
        ivColor.setBackgroundColor(anIntColor);



    }

}


/*activity_color.xml*/
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/ivColor"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />


</LinearLayout>

 

 

Creating a Color instance

we can represent a color by using the instance of the Color class . To create an instance of the color class , we must use the valueOf method . The valueOf methods will create a Color instance that represents a 64 bit color .

The methods

valueOf(float r, float g, float b)
valueOf(float r, float g, float b, float a)
valueOf(int)

will create an SRGB color represented by the Color instance . so each color component will take 8 bit . The methods

valueOf(float r, float g, float b, float a , ColorSpace space) 
valueOf(long)

will create an rgb color where each color is represented by 16 bits , the alfa channel is 10 bits , and the color space is 6 bits .

/*ColorActivity.java*/

package com.twiserandom.whatisacolor;


import android.graphics.Color;
import android.graphics.ColorSpace;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

public class ColorActivity extends AppCompatActivity {
    ImageView ivColor;

    @RequiresApi(api = Build.VERSION_CODES.O) /*Long Color can only be used for android version O or higher */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_color);

        /*Get the reference for the color imageViews*/
        ivColor = (ImageView) findViewById(R.id.ivColor);

        /*get rgb colorspace*/
        ColorSpace srgb = ColorSpace.get(ColorSpace.Named.SRGB);

        /*create a Color instance */
        Color color = Color.valueOf(0, 1, 1, 1, srgb);

        /*
        get a 32 bit color from a color instance
        */
        @ColorInt int anIntColor = color.toArgb();
        ivColor.setBackgroundColor(anIntColor);


    }

}


/*activity_color.xml*/
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/ivColor"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />


</LinearLayout>