如何在TextView中设置文本的自动反转颜色?

Sem*_*nid 2 android

例如,如果背景为白色,则文本颜色将为黑色。如果BG为黑色,则文本为白色。蓝色BG,黄色文本等。 更新:

// method in MyActivity class
void changeBackgroundColor(int newColor) {
    activityLayout.setBackgroundColor(newColor);
    int invertingColor = ColorInvertor.invert(newColor);
    someTextView.setTextColor(invertingColor);
}
Run Code Online (Sandbox Code Playgroud)

如果我致电activity.changeBackgroundColor(Color.WHITE),则someTextView必须将文本颜色更改为黑色,即ColorInvertor.invert(Color.WHITE) == Color.BLACKColorInvertor.invert(Color.BLACK) == Color.WHITE等等。

小智 5

获取您的颜色的rgb值,并从255中减去它们:

yourColor = Color.rgb(0,130,20);

invertedRed = 255 - 0;
invertedGreen = 255 - 130;
invertedBlue = 255 - 20;

text.setTextColor(Color.rgb(invertedRed,invertedGreen,invertedBlue));
Run Code Online (Sandbox Code Playgroud)

如果要使用十六进制值,请参见如何从Java中的十六进制颜色代码获取RGB值。