[英]How to generate Color code with UUID in Java
I want to create random color code with UUID in java, and i could not find best code for my problem. 我想在Java中使用UUID创建随机颜色代码,但找不到适合我问题的最佳代码。
Sample code for C# with GUID 带有GUID的C#的示例代码
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;
}
Here is an alternative : 这是一个替代方案:
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();
}
Answer for Android 适用于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();
}
You can do something like this: 您可以执行以下操作:
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;
}
You could also use the most significant bits from the UUID and generate 4 colours from each one, since this is only using a quarter half of the bits. 您还可以使用UUID中的最高有效位,并从每个位生成4种颜色,因为这仅使用了四分之一的位。
[Edited to only use 1 byte for each colour component.] [编辑为每个颜色分量仅使用1个字节。]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.