android把数字转换成字符串,如何在Android中将颜色整数转换为十六进制字符串?...

如何在Android中将颜色整数转换为十六进制字符串?

我有一个从android.graphics.Color生成的整数

整数的值为-16776961

如何将此值转换为格式为#RRGGBB的十六进制字符串

简单地说:我想从-16776961输出#0000FF

注意:我不希望输出包含alpha,我也尝试过这个例子而没有任何成功

7个解决方案

397 votes

掩码确保你只获得RRGGBB,%06X为你提供零填充十六进制(总是6个字符长):

String hexColor = String.format("#%06X", (0xFFFFFF & intColor));

Josh answered 2019-04-13T18:17:50Z

48 votes

尝试Integer.toHexString()

资源:在Java中,如何将字节数组转换为十六进制数字字符串,同时保持前导零?

ming_codes answered 2019-04-13T18:18:21Z

18 votes

我相信我已找到答案,此代码将整数转换为十六进制字符串并删除alpha。

Integer intColor = -16895234;

String hexColor = "#" + Integer.toHexString(intColor).substring(2);

注意,如果您确定删除alpha不会影响任何内容,请仅使用此代码。

Bosah Chude answered 2019-04-13T18:18:53Z

7 votes

这就是我做的

int color=//your color

Integer.toHexString(color).toUpperCase();//upercase with alpha

Integer.toHexString(color).toUpperCase().substring(2);// uppercase without alpha

谢谢你们的回答做了这件事

Diljeet answered 2019-04-13T18:19:24Z

3 votes

使用此方法Integer.toHexString,使用Color.parseColor时,某些颜色可能会出现Unknown颜色异常。

使用此方法String.format(“#%06X”,(0xFFFFFF& intColor)),您将失去alpha值。

所以我推荐这种方法:

public static String ColorToHex(int color) {

int alpha = android.graphics.Color.alpha(color);

int blue = android.graphics.Color.blue(color);

int green = android.graphics.Color.green(color);

int red = android.graphics.Color.red(color);

String alphaHex = To00Hex(alpha);

String blueHex = To00Hex(blue);

String greenHex = To00Hex(green);

String redHex = To00Hex(red);

// hexBinary value: aabbggrr

StringBuilder str = new StringBuilder("#");

str.append(alphaHex);

str.append(blueHex);

str.append(greenHex);

str.append(redHex );

return str.toString();

}

private static String To00Hex(int value) {

String hex = "00".concat(Integer.toHexString(value));

return hex.substring(hex.length()-2, hex.length());

}

Simon answered 2019-04-13T18:20:02Z

1 votes

ARGB颜色到十六进制字符串的整数值:

String hex = Integer.toHexString(color); // example for green color FF00FF00

十六进制字符串到ARGB颜色的整数值:

int color = (Integer.parseInt( hex.substring( 0,2 ), 16) << 24) + Integer.parseInt( hex.substring( 2 ), 16);

Style-7 answered 2019-04-13T18:20:33Z

0 votes

String int2string = Integer.toHexString(INTEGERColor); //to ARGB

String HtmlColor = "#"+ int2string.substring(int2string.length() - 6, int2string.length()); // a stupid way to append your color

chundk answered 2019-04-13T18:20:50Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值