c# - 从字符串生成唯一的十六进制颜色
问题描述
我想知道是否有任何方法可以根据指定的字符串生成随机的唯一颜色。我已经研究了 JavaScript 实现,但我需要一个 C# 中的实现。输入字符串“1233A”应始终返回相同的输出十六进制颜色。
解决方案
您可以使用对象的哈希值来生成颜色。
这是一个产生 RGBA 值的快速而肮脏的解决方案。
using System.Linq;
namespace System {
static class StringExtensions {
public static string ToHexColor(this string text) {
if (text == null) text = string.Empty;
int hash = text.GetHashCode();
return $"#{hash:X8}";
}
}
}
你可以使用它
string colorString = "My random string".ToHexColor();
推荐阅读
- android - 从不同帐户在 Google Play Store 上发布的两个 apk 文件可以由同一个密钥/密钥库签名吗?
- elasticsearch - ElasticSearch 关键字使用
- c# - 多线程添加数据时,BlockingCollection队列的数据顺序是否有保证?
- java - 上传具有不同扩展名 firebase 存储的多个文件
- android - 如何从列表视图中的标记颜色开始?
- angular - Angular2/4/6 将自定义管道过滤列表从 HTML 传递到组件
- xtext - Orion Web 编辑器中的 CTRL+SPACE 未触发 Xtext Content Assist
- javascript - 在 json 对象中循环 json 字符串
- swift - 计数对象数组错误
- java - 在订阅者线程中调用 Thread.Sleep 会导致发布者线程休眠