如何从我在View对象上使用的自定义colors.xml中获取颜色十六进制代码?

时间:2022-09-25 18:43:56

So I have custom colors.xml:

所以我有自定义colors.xml:

<color name="yellow">#FFFF00</color>
<color name="pink">#FF00FF</color>
<color name="red">#FF0000</color>
....................

If I used a color on an object (i.e. View) to color its background how can I get back the hex code what is in the tags? I mean I colored the view with yellow and I would like to know what hex code has that object -> #FFFF00

如果我在对象(即视图)上使用颜色为其背景着色,我如何才能找回标记中的十六进制代码?我的意思是我用黄色着色视图,我想知道十六进制代码有什么对象 - >#FFFF00

How can I do that?

我怎样才能做到这一点?

1 个解决方案

#1


0  

RelativeLayout re=(RelativeLayout)rootView.findViewById(R.id.idStack);
ColorDrawable colorDrawable=(ColorDrawable)re.getBackground();
String hexcolor=Integer.toHexString(colorDrawable.getColor());

hexcolor -> FFFF00

hexcolor - > FFFF00

UPDATE

In order to get the name of the color (#ff0000->RED), assuming that you're not doing anything too complicated since you provided that color.xml example in your question you should do this:

为了得到颜色的名称(#ff0000-> RED),假设你没有做任何太复杂的事情,因为你在问题中提供了color.xml示例,你应该这样做:

//Create a map of the colors you'll need
Map<Integer,String> mycolors=new HashMap<Integer, String>(){
 {
    //Color constants at http://developer.android.com/reference/android/graphics/Color.html#BLACK
    put(-16777216,"BLACK");
    put(-256,"YELLOW");
    ...and so on... 
 }
};

//Get the color name from your map
String colorname=mycolors.get(Color.parseColor("#"+hexcolor));
//colorname -> YELLOW    

Otherwise since the above snippet finds the exact match, you could try finding the closest color by using best match algorithm like this one for example: Best algorithm for matching colours.

否则,由于上面的代码段找到了完全匹配,您可以尝试使用最佳匹配算法找到最接近的颜色,例如:匹配颜色的最佳算法。

#1


0  

RelativeLayout re=(RelativeLayout)rootView.findViewById(R.id.idStack);
ColorDrawable colorDrawable=(ColorDrawable)re.getBackground();
String hexcolor=Integer.toHexString(colorDrawable.getColor());

hexcolor -> FFFF00

hexcolor - > FFFF00

UPDATE

In order to get the name of the color (#ff0000->RED), assuming that you're not doing anything too complicated since you provided that color.xml example in your question you should do this:

为了得到颜色的名称(#ff0000-> RED),假设你没有做任何太复杂的事情,因为你在问题中提供了color.xml示例,你应该这样做:

//Create a map of the colors you'll need
Map<Integer,String> mycolors=new HashMap<Integer, String>(){
 {
    //Color constants at http://developer.android.com/reference/android/graphics/Color.html#BLACK
    put(-16777216,"BLACK");
    put(-256,"YELLOW");
    ...and so on... 
 }
};

//Get the color name from your map
String colorname=mycolors.get(Color.parseColor("#"+hexcolor));
//colorname -> YELLOW    

Otherwise since the above snippet finds the exact match, you could try finding the closest color by using best match algorithm like this one for example: Best algorithm for matching colours.

否则,由于上面的代码段找到了完全匹配,您可以尝试使用最佳匹配算法找到最接近的颜色,例如:匹配颜色的最佳算法。