简体   繁体   中英

How to create an ARGB_8888 pixel value?

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 ?
}

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.

文档

(alpha << 24) | (red << 16) | (green << 8) | blue

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).

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM