算法生成唯一的颜色 [英] Algorithm For Generating Unique Colors
问题描述
我在寻找一种算法,会产生一系列的颜色,这样的颜色将被广泛分布地(因此他们不会轻易被混淆)。
I am looking for an algorithm that will generate a series of colors so that the colors will be as widely distributed as possible (so they won't easily be mixed up).
我有一系列具有ID的数从1对象我想重新present每一种具有不同的,美观的,颜色不会得到易与它的邻居。颜色不应该一定是随机的,但。我想获得相同的颜色,每次我输入相同的ID。
I have a series of objects that have IDs that count up from 1. I would like to represent each of these with a different, aesthetically pleasing, color that won't get easily confused with its neighbors. The colors should not necessarily be random though. I would like to get the same color each time I input the same ID.
推荐答案
有没有可能的要素的数量有一个合理的下界?一个快速和简单的解决方法就是存储利用项目的ID颜色值的数组。假定你有一个相对较低的颜色数量,你肯定,你将不会超过一定数量的物品,但是。
Does the number of possible elements have a reasonable low bound? One quick and easy solution is to just store an array of color values using the ID of the item. That assumes that you have a relatively low amount of colors, and you're certain that you won't go above a certain number of items, however.
如果你想生成的颜色,而不是使用列表,一招,使他们有一个一致的,体面的外观是采用HSB生成它们。 $ P $对 - 定义一个亮度和饱和度,然后基部色调值关的ID的一些功能(这可以是各种各样的事情取决于打算多少ID来有,但一定量乘以ID(和改装当其超过255!)是一个良好的粗糙的方法。用这种方法的颜色将所有的对准在饱和度和亮度而言但他们会各自具有不同的颜色。
If you want to generate colors rather than use a list, one trick to make them have a consistent and decent look is to generate them using HSB. Pre-define a brightness and saturation, then base the hue value off some function of the ID (this can be a variety of things depending on how many IDs you plan to have, but multiplying the ID by some amount (and modding when it exceeds 255!) is a good rough approach. With this approach the colors will all "align" in terms of saturation and brightness but they'll each have a distinct color.
我有点无聊的工作,所以我掀起一起快速的解决方案:
I'm a bit bored at work, so I whipped together a fast solution:
class HsbColor
{
public int Hue { get; set; }
public int Saturation { get; set; }
public int Brightness { get; set; }
public Color ToRGB
{
// left as exercise to the reader...
}
}
public class Item
{
public int Id { get; set; }
private static const byte EXPECTED_MAX = 15;
private static int HUE_FACTOR = 255 / EXPECTED_MAX;
public HsbColor Color
{
get {
var color = new HsbColor() { Saturation = 175, Brightness = 175 };
color.Hue = (Id * HUE_FACTOR) % 255;
return color;
}
}
}
这篇关于算法生成唯一的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!