How to use the “long” color?
Android API 26 introduces a new way to handle color:
Color longs are a representation introduced in Android O to store
colors in different color spaces, with more precision than color ints.
Now we can use the new color space, like this:
long longGreenColor = Color.pack(0.0f, 3.1415f, 0.0f, 1.0f, ColorSpace.get(ColorSpace.Named.LINEAR_EXTENDED_SRGB));
Nice, very long color. Now what?
- It cannot be used without
android.graphics.Canvas
- Can’t be used without
android.graphics.Paint
- It cannot be used without
android.graphics.Bitmap
How do I use long colors when drawing?
For example:
Bitmap bitmap = Bitmap.createBitmap(20, 20, Bitmap.Config.RGBA_F16, true, ColorSpace.get(ColorSpace.Named.LINEAR_EXTENDED_SRGB));
long longColor = Color.pack(0.0f, 3.1415f, 0.0f, 1.0f, ColorSpace.get(ColorSpace.Named.LINEAR_EXTENDED_SRGB));
bitmap.eraseColor(longColor);//ERROR
bitmap.eraseColor(Color.toArgb(longColor));//BAD!
bitmap.eraseColor((int) longColor);//WRONG!!!
Paint paint = new Paint();
paint.setColor(longColor);//ERROR
Canvas canvas = new Canvas(bitmap);
canvas.drawPoint(1, 1, paint);
Solution
I know this issue has been around for a long time (not ColorLong :D), but did you scroll down further down the docs? …
There is a dedicated section in Color
About these colors.
For example, you can use the static method Color.valueOf(long)
Convert from long
to Color
or just use non-static methods Paint.setColor(long)
Use it directly.
You can use static > Color.pack(float, float, float) creates a color of type long
, for example. That’s in the Encoding section
In the Decoding section it says you can use things like static Color.alpha(long)
and the like The component
of the long color (in this case, the alpha component).
Hope this helps.