Android中的位运算场景

401 阅读3分钟

「这是我参与2022首次更文挑战的第4天,活动详情查看:2022首次更文挑战

Android中的位运算场景

上一篇文章讲了位运算的优势,虽然在代码中我们很少使用位运算,但在安卓系统的代码中位运算出现频率也很高,来看看哪些地方用到了位运算。

颜色值的位运算

RGB 是一种颜色表示格式,R代表red红色,G代表green绿色,B代表blue蓝色,通过调节红绿蓝的颜色数值,可以表示各种颜色。

颜料的三原色是红黄蓝,光学的三原色是红绿蓝。 所以通过调节RGB,能够表示出各种颜色。

RGB的数据结构是这样的,比如 255,255,255 == #ffffff == 白色 0,0,0 == #000000 == 黑色

ARGB 就是加了透明通道的颜色数值。A代alpha(透明度)

ARGB的每个数值的范围都是0-255,这也是一个字节的范围,java中的一个int可以放4个字节,所以一个int的颜色值,就可以完整表示每一个颜色!

上代码

 int color = bitmap.getPixel(0, 0);
 int alpha = Color.alpha(color);
 int red = Color.red(color);
 int green = Color.green(color);
 int blue = Color.blue(color);

除了获取bitmap中像素的代码。 还有其它的转换方式。


// #FFB6C1转成Int
int color = Color.parseColor("#FFB6C1") // 或者直接写成 0xFFFFB6C1
// ARGB转Int
int color = Color.argb(255, 255, 255, 255);
// 获取color.xml的颜色资源
int color = getResources().getColor(R.color.red);

我们得到的color 值是一个int类型的颜色。 我们通过该颜色可以获取到 ARGB各项的值。

所以对应获取的方法是这样:


    /**
     * Return the alpha component of a color int. This is the same as saying
     * color >>> 24
     */
    @IntRange(from = 0, to = 255)
    public static int alpha(int color) {
        return color >>> 24;
    }

    /**
     * Return the red component of a color int. This is the same as saying
     * (color >> 16) & 0xFF
     */
    @IntRange(from = 0, to = 255)
    public static int red(int color) {
        return (color >> 16) & 0xFF;
    }

    /**
     * Return the green component of a color int. This is the same as saying
     * (color >> 8) & 0xFF
     */
    @IntRange(from = 0, to = 255)
    public static int green(int color) {
        return (color >> 8) & 0xFF;
    }

    /**
     * Return the blue component of a color int. This is the same as saying
     * color & 0xFF
     */
    @IntRange(from = 0, to = 255)
    public static int blue(int color) {
        return color & 0xFF;
    }

代码解读 >>> 代表无符号右移。 color >>> 24 也可以表示成 color >> 24 & oxff

0xff 代表每次取8个位

组件位置的位运算

大家都经常在布局中这么写

android:layout_gravity="bottom|right"

layout_gravity 是一个属性,对应的值是bottom|right,一个属性要表示多个值,所以在位上面,它们是错开的。

 <!-- Push object to the top of its container, not changing its size. -->
        <flag name="top" value="0x30" />
        <!-- Push object to the bottom of its container, not changing its size. -->
        <flag name="bottom" value="0x50" />
        <!-- Push object to the left of its container, not changing its size. -->
        <flag name="left" value="0x03" />
        <!-- Push object to the right of its container, not changing its size. -->
        <flag name="right" value="0x05" />

既然要错开,所以就要用到 | 这个运算符,让他们都保留下来,比如例子中的 bottom|right

bottom = 0x50; right = 0x05

这是 16进制,换算成2进制

0011 0010 bottom
0000 0101 right
————————
0011 0111 state

那么对应取值就是: bottom = bottom & right right = state & right

所以我们就能得到对应的原始值了。