Android에서 색 정수를 16진수 문자열로 변환하는 방법
I have a integer at the integer가 있습니다.android.graphics.Color
Integer의 값은 -16776961입니다.
이 값을 #RGBB 형식의 16진수 문자열로 변환하려면 어떻게 해야 합니까?
간단히 말하면:#0000을 출력하고 싶다.-16776961부터의 FF
주의: 출력에 알파벳을 포함하지 않도록 하고, 이 예도 시도해 보았으나 성공하지 못했습니다.
마스크를 사용하면 RRGBB만 얻을 수 있으며 %06X는 0 패드의 16진수(항상 6자 길이)를 제공합니다.
String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
Integer.toHexString()을 사용해 보십시오.
출처: Java에서는 선행 0을 유지하면서 바이트 배열을 16진수 문자열로 변환하려면 어떻게 해야 합니까?
답을 찾은 것 같습니다. 이 코드는 정수를 16진수 문자열로 변환하고 알파를 제거합니다.
Integer intColor = -16895234;
String hexColor = "#" + Integer.toHexString(intColor).substring(2);
알파를 제거해도 아무런 영향이 없을 경우에만 이 코드를 사용하십시오.
내가 한 일은 이렇다.
int color=//your color
Integer.toHexString(color).toUpperCase();//upercase with alpha
Integer.toHexString(color).toUpperCase().substring(2);// uppercase without alpha
고마워, 얘들아 대답해주렴
16진수 문자열에 대한 ARGB 색상의 정수 값:
String hex = Integer.toHexString(color); // example for green color FF00FF00
ARGB 색상의 16진수 문자열에서 정수 값:
int color = (Integer.parseInt( hex.substring( 0,2 ), 16) << 24) + Integer.parseInt( hex.substring( 2 ), 16);
알파가 없는 색상에 사용할 수 있습니다.
String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
또는 알파가 있는 경우:
String hexColor = String.format("#%08X", (0xFFFFFFFF & intColor));
Integer.toHexString 메서드를 사용하면 Color.parseColor를 사용할 때 일부 색에 대해 Unknown color 예외가 발생할 수 있습니다.
그리고 이 방법으로 String.format("#%06X", (0xFFFFFF & intColor)를 지정하면 알파 값이 손실됩니다.
따라서 다음 방법을 권장합니다.
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());
}
사용하시는 경우Integer.toHexString
다음과 같은 색상을 변환할 때 0을 놓치게 됩니다.0xFF000123
안드로이드 전용 클래스도 자바도 필요 없는 코틀린 기반 솔루션입니다.멀티플랫폼 프로젝트에서도 사용할 수 있습니다.
fun Int.toRgbString(): String =
"#${red.toStringComponent()}${green.toStringComponent()}${blue.toStringComponent()}".toUpperCase()
fun Int.toArgbString(): String =
"#${alpha.toStringComponent()}${red.toStringComponent()}${green.toStringComponent()}${blue.toStringComponent()}".toUpperCase()
private fun Int.toStringComponent(): String =
this.toString(16).let { if (it.length == 1) "0${it}" else it }
inline val Int.alpha: Int
get() = (this shr 24) and 0xFF
inline val Int.red: Int
get() = (this shr 16) and 0xFF
inline val Int.green: Int
get() = (this shr 8) and 0xFF
inline val Int.blue: Int
get() = this and 0xFF
컬러 피커 라이브러리의 알파 문제 수정.
첫 번째 색상을 선택했을 때 정수 값이 반환되는 경우 16진수 색으로 변환됩니다.
String hexVal = String.format("#%06X", (0xFFFFFFFF &
color)).toUpperCase();
int length=hexVal.length();
String withoutHash=hexVal.substring(1,length);
while (withoutHash.length()<=7)
{
withoutHash="0"+withoutHash;
}
hexVal ="#"+withoutHash;
String int2string = Integer.toHexString(INTEGERColor); //to ARGB
String HtmlColor = "#"+ int2string.substring(int2string.length() - 6, int2string.length()); // a stupid way to append your color
콜틴에서는 이 방법을 사용한다.
var hexColor = "#${Integer.toHexString(ContextCompat.getColor(context, R.color.colorTest))}"
Simon의 솔루션은 잘 작동하며, 알파가 지원되며 R, G, B, A, 16진수에서 선행하는 "제로" 값을 가진 컬러 케이스도 무시되지 않습니다.Java Color에서 16진수 문자열로 변환하기 위해 약간 변경된 버전은 다음과 같습니다.
public static String ColorToHex (Color color) {
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
int alpha = color.getAlpha();
String redHex = To00Hex(red);
String greenHex = To00Hex(green);
String blueHex = To00Hex(blue);
String alphaHex = To00Hex(alpha);
// hexBinary value: RRGGBBAA
StringBuilder str = new StringBuilder("#");
str.append(redHex);
str.append(greenHex);
str.append(blueHex);
str.append(alphaHex);
return str.toString();
}
private static String To00Hex(int value) {
String hex = "00".concat(Integer.toHexString(value));
hex=hex.toUpperCase();
return hex.substring(hex.length()-2, hex.length());
}
또 다른 솔루션은 다음과 같습니다.
public static String rgbToHex (Color color) {
String hex = String.format("#%02x%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha() );
hex=hex.toUpperCase();
return hex;
}
언급URL : https://stackoverflow.com/questions/6539879/how-to-convert-a-color-integer-to-a-hex-string-in-android
'programing' 카테고리의 다른 글
PHP cURL은 단일 요청으로 응답 헤더와 본문을 검색할 수 있습니까? (0) | 2022.09.15 |
---|---|
preg_replace를 사용하여 영숫자가 아닌 모든 문자 제거 (0) | 2022.09.15 |
MySQL 프로세스 목록을 찾아서 프로세스를 종료하려면 어떻게 해야 합니까? (0) | 2022.09.15 |
"Class.forName()"과 "Class.forName().newInstance()"의 차이점은 무엇입니까? (0) | 2022.09.15 |
MariaDB convert_tz maketime (0) | 2022.09.15 |