首页 > 解决方案 > 从字符串生成唯一的十六进制颜色

问题描述

我想知道是否有任何方法可以根据指定的字符串生成随机的唯一颜色。我已经研究了 JavaScript 实现,但我需要一个 C# 中的实现。输入字符串“1233A”应始终返回相同的输出十六进制颜色。

标签: c#.netalgorithm

解决方案


您可以使用对象的哈希值来生成颜色。

这是一个产生 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();

推荐阅读