gpt4 book ai didi

java - 如何在java中将rgb颜色转换为int

转载 作者:搜寻专家 更新时间:2023-10-30 19:47:45 24 4
gpt4 key购买 nike

Paint.setColor 需要一个整数。但我拥有的是一个 Color 对象。我在 Java 中没有看到 color.getIntValue() ?那我该怎么做呢?我想要的是像

public Something myMethod(Color rgb){
myPaint.setColor(rgb.getIntValue());
...
}

更正:android.graphics.Color; 我认为将 android 作为标签之一就足够了。但显然不是。

最佳答案

首先,android.graphics.Color 是一个仅由静态方法组成的类。您如何以及为何创建新的 android.graphics.Color 对象? (这完全没用,对象本身不存储任何数据)

但无论如何...我假设您使用的是一些实际存储数据的对象...

一个整数由 4 个字节组成(在 java 中)。查看标准 java Color 对象中的函数 getRGB(),我们可以看到 java 将每种颜色按 ARGB(Alpha-Red-Green-Blue)的顺序映射到整数的一个字节。我们可以使用自定义方法复制此行为,如下所示:

public int getIntFromColor(int Red, int Green, int Blue){
Red = (Red << 16) & 0x00FF0000; //Shift red 16-bits and mask out other stuff
Green = (Green << 8) & 0x0000FF00; //Shift Green 8-bits and mask out other stuff
Blue = Blue & 0x000000FF; //Mask out anything not blue.

return 0xFF000000 | Red | Green | Blue; //0xFF000000 for 100% Alpha. Bitwise OR everything together.
}

这假设您可以以某种方式检索单独的红色、绿色和蓝色分量,并且您为颜色传递的所有值都是 0-255。

如果您的 RGB 值是 0 到 1 之间的浮点百分比形式,请考虑以下方法:

public int getIntFromColor(float Red, float Green, float Blue){
int R = Math.round(255 * Red);
int G = Math.round(255 * Green);
int B = Math.round(255 * Blue);

R = (R << 16) & 0x00FF0000;
G = (G << 8) & 0x0000FF00;
B = B & 0x000000FF;

return 0xFF000000 | R | G | B;
}

正如其他人所说,如果您使用的是标准 java 对象,只需使用 getRGB();

如果您决定正确使用 android 颜色类,您还可以:

int RGB = android.graphics.Color.argb(255, Red, Green, Blue); //Where Red, Green, Blue are the RGB components. The number 255 is for 100% Alpha

int RGB = android.graphics.Color.rgb(Red, Green, Blue); //Where Red, Green, Blue are the RGB components.

正如其他人所说...(第二个函数假设 100% alpha)

这两种方法基本上与上面创建的第一个方法做同样的事情。

关于java - 如何在java中将rgb颜色转换为int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18022364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com