2011-10-16 36 views
6

我在應用程序中引入了「標記」功能,我允許顯示標記的方法之一是將文本設置爲用戶爲每個選擇的顏色。我的應用程序有三個主題,背景爲白色,黑色和類似筆記本的棕色(未來可能會改變/增長)。如果能夠輕鬆地對比背景,我希望能夠以其原始顏色顯示標籤,否則僅爲每個主題使用默認文本顏色。Android/Java:確定文本顏色是否會與背景混合?

我寫了一個幫助函數來幫助我確定文本是否被遮罩,但它不是100%正確的(我希望它確定顏色是否將基於所有三個hsv組件進行遮罩,並且正確現在飽和度比較無效)。代碼如下。

public static boolean colorWillBeMasked(int color, Application app){ 

     float[] hsv = new float[3]; 
     Color.colorToHSV(color, hsv); 
     //note 0, black 1, white 2 
     int theme = app.api.getThemeView(); 
     System.out.println("h=" +hsv[0]+ ", s=" +hsv[1]+ ", v=" +hsv[2]+", theme="+theme); 

     if(android.R.color.transparent == color) return true; 
     // color is dark 
     if(hsv[2] <= .2){ 
      if(theme == 1) return true; 
     } 
     // color is light 
     else if(hsv[2] >= .8) { 
      if(theme == 2) return true; 
     } 
     return false; 
    } 

當調用與藍色,紅色,透明,黑色,黃色和綠色的輸出如下所示(分別)這樣的功能:

  • H = 0.0,S = 1.0,V = 1.0,主題= 1
  • H = 229.41177,S = 1.0,v = 1.0,主題= 1
  • H = 267.6923,S = 1.0,v = 0.050980393,主題= 1
  • H = 0.0,S = 0.0, v = 0.0,主題= 1
  • h = 59.529 41,S = 1.0,V = 1.0,主題= 1
  • H = 111.29411,S = 1.0,V = 1.0,主題= 1

我的問題是:根據色調,飽和度和值,如何你能否確定以某種方式着色的文本是否會顯示在白色背景上,而不是黑色背景上,還是會被遮罩?請把我的算法和改進,或幫助我創建一個新的。

在此先感謝。我想出了

+0

感謝您的評論?你甚至沒有提出問題,但是:不客氣。 – Stephan

+0

更新了文字,對不起,我不清楚。 – Blaskovicz

回答

3

解決方案:

我最終使用的算法發現on this blog重新定義我的功能如下:然後我調整了每一端的亮度截止。希望這可以幫助某人。

public static boolean colorWillBeMasked(int color, Application app){ 
    if(android.R.color.transparent == color) return true; 

    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); 

    System.out.println("COLOR: " + color + ", BRIGHT: " + brightness); 
    //note 0,black 1,classic 2 
    int theme = app.api.getThemeView(); 

    // color is dark 
    if(brightness <= 40){ 
     if(theme == 1) return true; 
    } 
    // color is light 
    else if (brightness >= 215){ 
     if(theme == 2) return true; 
    } 
    return false; 
} 
+0

請注意,源的亮度係數來自[另一個來源](http://alienryderflex.com/hsp.html),其本身在此期間被改變以指定其作者自「被告知......」以來的不同係數更精確「:.299,.587,.114。 –