2016-07-15 84 views
-1

我想在Java中使用UUID創建隨機顏色代碼,並且找不到最適合我的問題的代碼。對於C#與GUID如何在Java中使用UUID生成顏色代碼

public static Color ColorFromGuid(UUID id) 
{ 
    var values = id.ToByteArray().Select(b => (int)b); 
    int red = values.Take(5).Sum() % 255; 
    int green = values.Skip(5).Take(5).Sum() % 255; 
    int blue = values.Skip(10).Take(5).Sum() % 255; 

    Color color = Color.FromArgb(200, red, green, blue); 
    return color; 
} 
+0

看到http://stackoverflow.com/help/someone-answers – c0der

回答

0

示例代碼,你可以做這樣的事情:

public static Color colorFromGuid(UUID uuid) { 
    ByteBuffer bb = ByteBuffer.wrap(new byte[8]); 
    bb.putLong(uuid.getLeastSignificantBits()); 
    int red = bb.get(0) & 0xff; 
    int green = bb.get(1) & 0xff; 
    int blue = bb.get(2) & 0xff; 
    int alpha = bb.get(3) & 0xff; 

    Color color = new Color(red, green, blue, alpha); 
    return color; 
} 

你也可以從UUID使用最顯著位和每一個產生4種顏色,因爲這隻使用四分之一的比特。

[編輯,以只使用針對每個顏色分量1個字節。]

+0

我得到錯誤: 顏色()不能應用於 –

+0

那麼代碼工作正常,併產生隨機的顏色。你得到的堆棧跟蹤的第一行是什麼? –

+0

我在android.is中使用此方法它不同於android? –

1

下面是一個替代:

 public static void main(String[] args) { 

      getRandomColor(UUID.randomUUID()); 

     } 

     /** 
     * Method return a random color. 
     */ 
     public static Color getRandomColor(UUID id) { 

      byte[] bytes = UUID2Bytes(id); 

      int r= Math.abs(bytes[0]); 
      int g = Math.abs(bytes[1]); 
      int b = Math.abs(bytes[2]); 

      return new Color(r, g, b); 
     } 

     public static byte[] UUID2Bytes(UUID uuid) { 

      long hi = uuid.getMostSignificantBits(); 
      long lo = uuid.getLeastSignificantBits(); 
      return ByteBuffer.allocate(16).putLong(hi).putLong(lo).array(); 
     } 
+0

我們進口此類: import android.graphics.Color;如何解決問題? –

+0

Android不在問題的標籤中。如果你需要Android的解決方案,應該添加它。此外,我認爲根據SO規則,這需要成爲一個單獨的問題。 – c0der

0

回答爲Android

public int getRandomColor(UUID id) { 

     byte[] bytes = UUID2Bytes(id); 

     int r= Math.abs(bytes[0]); 
     int g = Math.abs(bytes[1]); 
     int b = Math.abs(bytes[2]); 
     int color = Color.argb(255, r, g, b); 
     Log.e("Color",color+""); 
     return color; 
    } 

    public byte[] UUID2Bytes(UUID uuid) { 

     long hi = uuid.getMostSignificantBits(); 
     long lo = uuid.getLeastSignificantBits(); 
     Log.e("UUID2Bytes",hi+" "+lo); 
     return ByteBuffer.allocate(16).putLong(hi).putLong(lo).array(); 
    }