[英]How to set auto inverting color of text in TextView?
例如,如果背景為白色,則文本顏色將為黑色。 如果 BG 為黑色,則文本將為白色。 藍色背景、黃色文字等更新:
// method in MyActivity class
void changeBackgroundColor(int newColor) {
activityLayout.setBackgroundColor(newColor);
int invertingColor = ColorInvertor.invert(newColor);
someTextView.setTextColor(invertingColor);
}
如果我調用activity.changeBackgroundColor(Color.WHITE)
,那么someTextView
必須將文本顏色更改為黑色,即ColorInvertor.invert(Color.WHITE) == Color.BLACK
和ColorInvertor.invert(Color.BLACK) == Color.WHITE
等
獲取顏色的 rgb 值並從 255 中減去它們:
yourColor = Color.rgb(0,130,20);
invertedRed = 255 - 0;
invertedGreen = 255 - 130;
invertedBlue = 255 - 20;
text.setTextColor(Color.rgb(invertedRed,invertedGreen,invertedBlue));
如果要使用十六進制值,請參閱如何從 Java 中的十六進制顏色代碼獲取 RGB 值
只需使用簡單的條件即可:
1.獲取顏色
2.檢查條件
3.設置顏色
獲取顏色:
TextView tv1;
tv1=(TextView)findViewById(R.id.tv1);
ColorDrawable tv1color = (ColorDrawable) tv1.getBackground();
如果您使用的是 Android 3.0+,則可以獲取顏色的資源 ID:
int tv1colorId = tv1color.getColor();
設置顏色:
TextView tv2;
tv2=(TextView)findViewById(R.id.tv2);
tv2.setBackgroundColor(0xFF00FF00);
然后根據需要設置條件:
if (tv1colorID == R.color.green) {
tv2.setBackgroundColor(color.WHITE); // As your choice color
}
您可以使用這些函數反轉顏色...
//color
public static String getHex(int intColor) {
String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
return hexColor;
}
public static String getRGBStringfromHex(String hexColor) {
int color = Color.parseColor(hexColor);
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
return red + "," + green + "," + blue;
}
public static int[] getRGBStringtoRGBInt(String splits[]) {
int list[] = new int[3];
list[0]=Integer.parseInt(splits[0]);
list[1]=Integer.parseInt(splits[1]);
list[2]=Integer.parseInt(splits[2]);
return list;
}
public static int getRGBColor(int rgb[]) {
int color = Color.rgb(rgb[0],rgb[1],rgb[2]);
return color;
}
public static String invertedRGBfromRGB(int rgb[]) {
int invertedRed = 255 - rgb[0];
int invertedGreen = 255 - rgb[1];
int invertedBlue = 255 - rgb[2];
return invertedRed + "," + invertedGreen + "," + invertedBlue;
}
public static int getColorFromRGBString(String color) {
ArrayList<Integer> list = new ArrayList<>();
String splits[] = color.split(Pattern.quote(","));
list.add(Integer.parseInt(splits[0]));
list.add(Integer.parseInt(splits[1]));
list.add(Integer.parseInt(splits[2]));
return Color.rgb(list.get(0), list.get(1), list.get(2));
}
好的,如果你轉換一個 int 顏色......
String rgb[]=getRGBStringfromHex(getHex(colorThatWanttoInvert)).split(",");
int desireinvertedcolor=getColorFromRGBString(invertedRGBfromRGB(getRGBStringtoRGBInt(rgb)));
希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.