Reputation: 147
In application's res/values/colors.xml file, a red color is defined in #AARRGGBB format:
<color name="red">#ffff0000</color>
How to use this color as an argument to glClearColor and other OpenGL ES functions? For example:
public void onSurfaceCreated(GL10 unused, EGLConfig config) {
GLES20.glClearColor(1.0f, 0.0f, 0.0f, 1.0f); // <-- How to connect R.color.red here?
}
Upvotes: 3
Views: 3657
Reputation: 54642
The Color
class has static methods to support this. If strColor
is a color in string format, which can be #RRGGBB
, #AARRGGBB
, or the name of a color, you can use the following to convert it to the values you need for OpenGL:
int intColor = Color.parseColor(strColor);
GLES20.glClearColor(Color.red(intColor) / 255.0f,
Color.green(intColor) / 255.0f,
Color.blue(intColor) / 255.0f);
Upvotes: 5
Reputation: 312
This is my solution to convert a color from HEX to glClearColor() format which is a float between 0 and 1.
First I convert the color to RGB, then I map that color from 0 to 1.
/* re-map RGB colors so they can be used in OpenGL */
private float[] map(float[]rgb) {
/* RGB is from 0 to 255 */
/* THIS is from 0 to 1 (float) */
// 1 : 2 = x : 4 >>> 2
/*
*
* 240 : 255 = x : 1
*
* */
float[] result = new float[3];
result[0] = rgb[0] / 255;
result[1] = rgb[1] / 255;
result[2] = rgb[2] / 255;
return result;
}
public float[] hextoRGB(String hex) {
float[] rgbcolor = new float[3];
rgbcolor[0] = Integer.valueOf( hex.substring( 1, 3 ), 16 );
rgbcolor[1] = Integer.valueOf( hex.substring( 3, 5 ), 16 );
rgbcolor[2] = Integer.valueOf( hex.substring( 5, 7 ), 16 );
return map(rgbcolor);
}
Usage:
//0077AB is HEX color code
float[] values = hextoRGB("#0077AB");
GLES20.glClearColor(values[0], values[1], values[2], 1.0f);
Upvotes: 0
Reputation: 2832
You should use shifts to isolate the individual bytes, cast them to floats and then divide to scale them down to the range 0.0f to 1.0f. It should look like this:
unsigned long uColor; // #AARRGGBB format
float fAlpha = (float)(uColor >> 24) / 0xFF
float fRed = (float)((uColor >> 16) & 0xFF) / 0xFF;
float fGreen = (float)((uColor >> 8) & 0xFF) / 0xFF;
float fBlue = (float)(uColor & 0xFF) / 0xFF;
GLES20.glClearColor(fRed, fGreen, fBlue, fAlpha);
Upvotes: 3