Reputation: 13077
Say I want to create an array of pixel values to pass into the createBitmap
method described here. I have three int values r, g, b
in the range 0 - 0xff. How do I transform those into an opaque pixel p
?
Does the alpha channel go in the high byte or the low byte?
I googled up the documentation but it only states that:
Each pixel is stored on 4 bytes. Each channel (RGB and alpha for translucency) is stored with 8 bits of precision (256 possible values.) This configuration is very flexible and offers the best quality. It should be used whenever possible.
So, how to write this method?
int createPixel(int r, int g, int b)
{
return ?
}
Upvotes: 2
Views: 5645
Reputation: 156434
It looks like the RGBA pixel format is pretty well documented and I'm assuming that's what the Android docs mean, just using a different name to match the channel membership position in the bit field:
Something like this should work:
int createPixel(int r, int g, int b) {
return createPixel(r, g, b, 0xff);
}
int createPixel(int r, int g, int b, int a) {
return (a<<24) | (r<<16) | (g<<8) | b;
}
Also, you might want to use a byte
instead of an int
to avoid overflow-type errors, or mask only the bits you want:
int createPixel(int r, int g, int b, int a) {
return ((a & 0xff) << 24)
| ((r & 0xff) << 16)
| ((g & 0xff) << 8)
| ((b & 0xff));
}
Although clamping the values to [0,255]
might make more sense.
Upvotes: 11
Reputation: 234807
This should work:
int createPixel(int r, int g, int b)
{
return 0xff000000 | (r << 16) | (g << 8) | b;
}
or, if you want to be baroque:
int createPixel(int r, int g, int b)
{
return (((((-1 << 8) | r) << 8) | g) << 8) | b;
}
Upvotes: 1
Reputation: 12737
First of all, your arguments should be bytes, not ints, but I guess this could be an implementation issue.
In general you would do something like
return b | r<<8 | g<<16 | 255<<24;
assuming your alpha is 255 (non-transparent).
Upvotes: 1
Reputation: 60681
From the docs:
(alpha << 24) | (red << 16) | (green << 8) | blue
Upvotes: 6