如何从十六进制颜色字符串获取颜色

发布于 2024-10-20 23:05:42 字数 160 浏览 2 评论 0原文

我想使用十六进制字符串(例如 "#FFFF0000")中的颜色来(比如说)更改布局的背景颜色。 Color.HSVToColor 看起来像是赢家,但它需要一个 float[] 作为参数。

我已经接近解决方案了吗?

I'd like to use a color from an hexa string such as "#FFFF0000" to (say) change the background color of a Layout.
Color.HSVToColor looks like a winner but it takes a float[] as a parameter.

Am I any close to the solution at all?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

岁吢 2024-10-27 23:05:42

尝试 Color 类方法:

public static int parseColor (String colorString)

来自 Android 文档

支持的格式有:#RRGGBB #AARRGGBB '红色'、'蓝色'、'绿色'、'黑色'、'白色'、'灰色'、'青色'、'洋红色'、'黄色'、'浅灰色' , '深灰色'

AndroidX: String.toColorInt()

Try Color class method:

public static int parseColor (String colorString)

From Android documentation:

Supported formats are: #RRGGBB #AARRGGBB 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray'

AndroidX: String.toColorInt()

赠佳期 2024-10-27 23:05:42

尝试:

myLayout.setBackgroundColor(Color.parseColor("#636161"));

Try:

myLayout.setBackgroundColor(Color.parseColor("#636161"));
三人与歌 2024-10-27 23:05:42

这个问题出现在许多与十六进制颜色相关的搜索中,所以我将在这里添加一个摘要。

来自 int Hex 颜色的颜色

采用 RRGGBBAARRGGBB 形式(alpha、红、绿、蓝)。根据我的经验,直接使用 int 时,您需要使用完整的 AARRGGBB 形式。如果您只有 RRGGBB 形式,则只需在其前面添加 FF 即可使 Alpha(透明度)完全不透明。以下是在代码中设置它的方法。在开头使用 0x 意味着它是十六进制而不是以 10 为基数。

int myColor = 0xFF3F51B5;
myView.setBackgroundColor(myColor);

来自字符串的颜色

正如其他人所指出的,您可以像这样使用 Color.parseColor

int myColor = Color.parseColor("#3F51B5");
myView.setBackgroundColor(myColor);

请注意,字符串必须以开头带有#。支持 RRGGBBAARRGGBB 格式。

来自 XML 的颜色

实际上,只要有可能,您就应该从 XML 中获取颜色。这是推荐的选项,因为它可以更轻松地更改应用程序的颜色。如果您在代码中设置了很多十六进制颜色,那么以后尝试更改它们会很痛苦。

Android 材料设计具有已配置十六进制值的调色板。

这些主题颜色在整个应用程序中使用,如下所示:

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="primary">#3F51B5</color>
  <color name="primary_dark">#303F9F</color>
  <color name="primary_light">#C5CAE9</color>
  <color name="accent">#FF4081</color>
  <color name="primary_text">#212121</color>
  <color name="secondary_text">#757575</color>
  <color name="icons">#FFFFFF</color>
  <color name="divider">#BDBDBD</color>
</resources>

如果您需要其他颜色,最好的做法是接下来是在 xml 中分两步定义颜色。首先命名十六进制值颜色,然后命名应用程序中应获得特定颜色的组件。这使得以后调整颜色变得容易。同样,这是在colors.xml中。

<color name="orange">#fff3632b</color>
<color name="my_view_background_color">@color/orange</color>

然后,当您想在代码中设置颜色时,请执行以下操作:

int myColor = ContextCompat.getColor(context, R.color.my_view_background_color);    
myView.setBackgroundColor(myColor);

Android 预定义颜色

Color 类附带了许多预定义的颜色常量。你可以像这样使用它。

int myColor = Color.BLUE;
myView.setBackgroundColor(myColor);

其他颜色为

  • Color.BLACK
  • Color.BLUE
  • Color.CYAN
  • Color.DKGRAY
  • Color.GRAY< /code>
  • Color.GREEN
  • Color.LTGRAY
  • Color.MAGENTA
  • Color.RED
  • Color.TRANSPARENT< /code>
  • Color.WHITE
  • Color.YELLOW

注释

This question comes up for a number of searches related to hex color so I will add a summary here.

Color from int

Hex colors take the form RRGGBB or AARRGGBB (alpha, red, green, blue). In my experience, when using an int directly, you need to use the full AARRGGBB form. If you only have the RRGGBB form then just prefix it with FF to make the alpha (transparency) fully opaque. Here is how you would set it in code. Using 0x at the beginning means it is hexadecimal and not base 10.

int myColor = 0xFF3F51B5;
myView.setBackgroundColor(myColor);

Color from String

As others have noted, you can use Color.parseColor like so

int myColor = Color.parseColor("#3F51B5");
myView.setBackgroundColor(myColor);

Note that the String must start with a #. Both RRGGBB and AARRGGBB formats are supported.

Color from XML

You should actually be getting your colors from XML whenever possible. This is the recommended option because it makes it much easier to make color changes to your app. If you set a lot of hex colors throughout your code then it is a big pain to try to change them later.

Android material design has color palates with the hex values already configured.

These theme colors are used throughout your app and look like this:

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="primary">#3F51B5</color>
  <color name="primary_dark">#303F9F</color>
  <color name="primary_light">#C5CAE9</color>
  <color name="accent">#FF4081</color>
  <color name="primary_text">#212121</color>
  <color name="secondary_text">#757575</color>
  <color name="icons">#FFFFFF</color>
  <color name="divider">#BDBDBD</color>
</resources>

If you need additional colors, a good practice to follow is to define your color in two steps in xml. First name the the hex value color and then name a component of your app that should get a certain color. This makes it easy to adjust the colors later. Again, this is in colors.xml.

<color name="orange">#fff3632b</color>
<color name="my_view_background_color">@color/orange</color>

Then when you want to set the color in code, do the following:

int myColor = ContextCompat.getColor(context, R.color.my_view_background_color);    
myView.setBackgroundColor(myColor);

Android Predefined colors

The Color class comes with a number of predefined color constants. You can use it like this.

int myColor = Color.BLUE;
myView.setBackgroundColor(myColor);

Other colors are

  • Color.BLACK
  • Color.BLUE
  • Color.CYAN
  • Color.DKGRAY
  • Color.GRAY
  • Color.GREEN
  • Color.LTGRAY
  • Color.MAGENTA
  • Color.RED
  • Color.TRANSPARENT
  • Color.WHITE
  • Color.YELLOW

Notes

披肩女神 2024-10-27 23:05:42

将该字符串转换为可在 setBackgroundColorsetTextColor 中使用的 int 颜色。

String string = "#FFFF0000";
int color = Integer.parseInt(string.replaceFirst("^#",""), 16);

16 表示它是十六进制,而不是常规的 0-9。结果应该是一样的

int color = 0xFFFF0000;

Convert that string to an int color which can be used in setBackgroundColor and setTextColor

String string = "#FFFF0000";
int color = Integer.parseInt(string.replaceFirst("^#",""), 16);

The 16 means it is hexadecimal and not your regular 0-9. The result should be the same as

int color = 0xFFFF0000;
梦过后 2024-10-27 23:05:42

它是

int color =  Color.parseColor("colorstring");

It's

int color =  Color.parseColor("colorstring");
迷荒 2024-10-27 23:05:42

试试这个:

vi.setBackgroundColor(Color.parseColor("#FFFF0000"));

Try this:

vi.setBackgroundColor(Color.parseColor("#FFFF0000"));
吾性傲以野 2024-10-27 23:05:42

我用它,它非常适合我设置我想要的任何颜色。

public static final int MY_COLOR = Color.rgb(255, 102, 153);

使用 0-255 为每种红色、绿色和蓝色设置颜色,然后在您想要使用该颜色的任何地方只需放置 MY_COLOR 而不是 Color.BLUE 或 Color.RED 或 Color 类提供的任何其他静态颜色。

只需在 Google 上搜索颜色图表,您就可以找到包含使用 0-255 的正确 RGB 代码的图表。

I use this and it works great for me for setting any color I want.

public static final int MY_COLOR = Color.rgb(255, 102, 153);

Set the colors using 0-255 for each red, green and blue then anywhere you want that color used just put MY_COLOR instead of Color.BLUE or Color.RED or any of the other static colors the Color class offers.

Just do a Google search for color chart and it you can find a chart with the correct RGB codes using 0-255.

孤单情人 2024-10-27 23:05:42

尝试此操作。

int colorInt = Color.parseColor("#FF00FFF0");
bg.setBackgroundColor(colorInt);

在 bg 是要为其设置背景颜色的视图或布局的情况下

Try this

int colorInt = Color.parseColor("#FF00FFF0");
bg.setBackgroundColor(colorInt);

where bg is a view or layout to which you want to set the background color.

荒岛晴空 2024-10-27 23:05:42

在 Xamarin 中
用这个

Control.SetBackgroundColor(global::Android.Graphics.Color.ParseColor("#F5F1F1"));

In Xamarin
Use this

Control.SetBackgroundColor(global::Android.Graphics.Color.ParseColor("#F5F1F1"));
﹏雨一样淡蓝的深情 2024-10-27 23:05:42

尝试改用 0xFFF000 并将其传递给 Color.HSVToColor 方法。

Try using 0xFFF000 instead and pass that into the Color.HSVToColor method.

美人如玉 2024-10-27 23:05:42

如果您在 XML 中定义了一种颜色并希望使用它来更改背景颜色或其他内容,则此 API 就是您正在寻找的颜色:

 ((TextView) view).setBackgroundResource(R.drawable.your_color_here);

在我的示例中,我将其用于 TestView

If you define a color in your XML and want to use it to change background color or something this API is the one your are looking for:

 ((TextView) view).setBackgroundResource(R.drawable.your_color_here);

In my sample I used it for TestView

黯淡〆 2024-10-27 23:05:42

我已经创建了一个完整的答案:

    /**
     * Input: Hex Value of ARGB, eg: "#FFFF00FF", "#FF00FF", "#F0F"
     * Output:  Float Color Array with  with red, green,
     * blue and alpha (opacity) values,
     * eg:  floatArrayOf(0.63671875f, 0.76953125f, 0.22265625f, 1.0f)
     */
    private fun getFloatArrayFromARGB(argb: String): FloatArray {
        val colorBase: Int = if (argb.length == 4) {
            val red = if (argb[1] == '0') 0 else 255
            val green = if (argb[2] == '0') 0 else 255
            val blue = if (argb[3] == '0') 0 else 255
            Color.rgb(red, green, blue)
        } else {
            Color.parseColor(argb)
        }
        val red = Color.red(colorBase)
        val green = Color.green(colorBase)
        val blue = Color.blue(colorBase)
        val alpha = Color.alpha(colorBase)
        return floatArrayOf(
            red / 255f,
            green / 255f,
            blue / 255f,
            alpha / 255f
        )
    }

用法

   private val colorValue = getFloatArrayFromARGB("#F0F")

希望它对某人有帮助

I Have created a Complete Answer :

    /**
     * Input: Hex Value of ARGB, eg: "#FFFF00FF", "#FF00FF", "#F0F"
     * Output:  Float Color Array with  with red, green,
     * blue and alpha (opacity) values,
     * eg:  floatArrayOf(0.63671875f, 0.76953125f, 0.22265625f, 1.0f)
     */
    private fun getFloatArrayFromARGB(argb: String): FloatArray {
        val colorBase: Int = if (argb.length == 4) {
            val red = if (argb[1] == '0') 0 else 255
            val green = if (argb[2] == '0') 0 else 255
            val blue = if (argb[3] == '0') 0 else 255
            Color.rgb(red, green, blue)
        } else {
            Color.parseColor(argb)
        }
        val red = Color.red(colorBase)
        val green = Color.green(colorBase)
        val blue = Color.blue(colorBase)
        val alpha = Color.alpha(colorBase)
        return floatArrayOf(
            red / 255f,
            green / 255f,
            blue / 255f,
            alpha / 255f
        )
    }

Usage:

   private val colorValue = getFloatArrayFromARGB("#F0F")

Hope it help somebody

伴随着你 2024-10-27 23:05:42

对于缩短的十六进制代码

int red = colorString.charAt(1) == '0' ? 0 : 255;
int blue = colorString.charAt(2) == '0' ? 0 : 255;
int green = colorString.charAt(3) == '0' ? 0 : 255;
Color.rgb(red, green,blue);

For shortened Hex code

int red = colorString.charAt(1) == '0' ? 0 : 255;
int blue = colorString.charAt(2) == '0' ? 0 : 255;
int green = colorString.charAt(3) == '0' ? 0 : 255;
Color.rgb(red, green,blue);
筱果果 2024-10-27 23:05:42

没有预定义的类可以直接实现从十六进制代码到颜色名称,因此您要做的就是尝试简单的键值对概念,遵循此代码。

String hexCode = "Any Hex code" //#0000FF

HashMap<String, String> color_namme = new HashMap<String, String>();
                        color_namme.put("#000000", "Black");
                        color_namme.put("#000080", "Navy Blue");
                        color_namme.put("#0000C8", "Dark Blue");
                        color_namme.put("0000FF", "Blue");
                        color_namme.put("000741", "Stratos");
                        color_namme.put("001B1C", "Swamp");
                        color_namme.put("002387", "Resolution Blue");
                        color_namme.put("002900", "Deep Fir");
                        color_namme.put("002E20", "Burnham");
                        for (Map.Entry<String, String> entry : color_namme.entrySet()) {
                            String key = (String) entry.getKey();
                            String thing = (String) entry.getValue();
                            if (hexCode.equals(key))
                                Color_namme.setText(thing); //Here i display using textview


                        }

There is no pre-defined class to implement directly from hex code to color name so what you have to do is Try key value pair concept simple, follow this code.

String hexCode = "Any Hex code" //#0000FF

HashMap<String, String> color_namme = new HashMap<String, String>();
                        color_namme.put("#000000", "Black");
                        color_namme.put("#000080", "Navy Blue");
                        color_namme.put("#0000C8", "Dark Blue");
                        color_namme.put("0000FF", "Blue");
                        color_namme.put("000741", "Stratos");
                        color_namme.put("001B1C", "Swamp");
                        color_namme.put("002387", "Resolution Blue");
                        color_namme.put("002900", "Deep Fir");
                        color_namme.put("002E20", "Burnham");
                        for (Map.Entry<String, String> entry : color_namme.entrySet()) {
                            String key = (String) entry.getKey();
                            String thing = (String) entry.getValue();
                            if (hexCode.equals(key))
                                Color_namme.setText(thing); //Here i display using textview


                        }

枕梦 2024-10-27 23:05:42

用于kotlin扩展函数

fun String.toColor(): Int? {
    return if (this.isNotEmpty()) {
        Color.parseColor(this)
    } else {
        null
    }

For kotlin extension function

fun String.toColor(): Int? {
    return if (this.isNotEmpty()) {
        Color.parseColor(this)
    } else {
        null
    }
魔法少女 2024-10-27 23:05:42

下面是一个用于 Jetpack Compose Color

import androidx.compose.ui.graphics.Color

typealias AndroidColor = android.graphics.Color

fun Color.Companion.fromHex(hexColorCode: String): Color {
    val processedColor = hexColorCode.uppercase().removePrefix("#")

    val colorInt = when (processedColor.length) {

        3 -> { // Short RGB format (#RGB)
            val (r, g, b) = processedColor.map { it.toString().repeat(2) }
            AndroidColor.parseColor("#$r$g$b")
        }

        4 -> { // Short ARGB format (#ARGB)
            val (a, r, g, b) = processedColor.map { it.toString().repeat(2) }
            AndroidColor.parseColor("#$a$r$g$b")
        }

        // Standard RGB or ARGB formats
        6, 8 -> AndroidColor.parseColor("#$processedColor")

        else -> {
            Color.Black.hashCode() // Default color if the input is not hex
        }
    }

    return Color(colorInt)
}

用法的精致 Kotlin 扩展函数:

val color = Color.fromHex("#80FF5733")

Here is a delicate Kotlin extension function for a Jetpack Compose Color

import androidx.compose.ui.graphics.Color

typealias AndroidColor = android.graphics.Color

fun Color.Companion.fromHex(hexColorCode: String): Color {
    val processedColor = hexColorCode.uppercase().removePrefix("#")

    val colorInt = when (processedColor.length) {

        3 -> { // Short RGB format (#RGB)
            val (r, g, b) = processedColor.map { it.toString().repeat(2) }
            AndroidColor.parseColor("#$r$g$b")
        }

        4 -> { // Short ARGB format (#ARGB)
            val (a, r, g, b) = processedColor.map { it.toString().repeat(2) }
            AndroidColor.parseColor("#$a$r$g$b")
        }

        // Standard RGB or ARGB formats
        6, 8 -> AndroidColor.parseColor("#$processedColor")

        else -> {
            Color.Black.hashCode() // Default color if the input is not hex
        }
    }

    return Color(colorInt)
}

Usage:

val color = Color.fromHex("#80FF5733")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文