2013-05-01 19 views
1

如何在android中檢查亮度?如何檢查android中的顏色亮度?

我有一個整數值的顏色。我想檢查這種顏色是暗色還是淺色,基於顏色的整數值。

if (checkColor == Color.RED || checkColor == Color.BLACK) { 

    //set fore color is white 

} else { 

    //set fore color is black 
} 

,而不是上面的代碼,我想改變

if (!isBrightColor(checkColor)) { 

    //set fore color is white 

} else { 

    //set fore color is black 
} 

private boolean isBrightColor(int checkColor){ 

    boolean rtnValue; 

    //How to check this color is bright or dark 

    return rtnValue; 

} 

回答

4

你應該試試這個....

public static boolean isBrightColor(int color) { 
    if (android.R.color.transparent == color) 
     return true; 

    boolean rtnValue = false; 

    int[] rgb = { Color.red(color), Color.green(color), Color.blue(color) }; 

    int brightness = (int) Math.sqrt(rgb[0] * rgb[0] * .241 + rgb[1] 
      * rgb[1] * .691 + rgb[2] * rgb[2] * .068); 

    // color is light 
    if (brightness >= 200) { 
     rtnValue = true;   
    } 

    return rtnValue; 
} 

參考: Android/Java: Determining if text color will blend in with the background?

+1

非常感謝您! !這段代碼非常有用。 – 2013-05-01 05:20:40

+1

第一行沒有任何意義。在'Color.red(color)'中,您將顏色視爲顏色int,並在'if(android.R.color.transparent == color)'中將顏色視爲顏色資源。如果你傳遞一種顏色,第一行永遠不會是真的。 – 2016-08-29 14:14:49