using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Autodesk.Revit.DB; namespace ShrlAlgoToolkit.Core.Assists { public class ColorAssist { public static Color GetDistinctColorById(ElementId id) { int hash = id.GetHashCode(); // 修正点:强制转换为 (int),利用 unchecked 溢出机制 // 2654435761 在 int 中就是 -1640531527 // unchecked 关键字确保在某些开启了溢出检查的项目配置中不会报错 unchecked { hash = hash * (int)2654435761; } // 2. 将哈希值映射到 0.0 - 1.0 的色相 (Hue) // 使用黄金分割比 0.6180339887... 累加可以让颜色在色环上分布最均匀 double goldenRatioConjugate = 0.618033988749895; double h = (hash * goldenRatioConjugate) % 1.0; // 保证 h 为正数 if (h < 0) h += 1.0; // 3. 固定饱和度 (S) 和 亮度 (V) 为较高值,保证颜色鲜艳 double s = 0.7; // 饱和度 0.0-1.0 double v = 0.9; // 亮度 0.0-1.0 // 4. HSV 转 Revit Color (RGB) return HsvToRgb(h, s, v); } // 辅助函数:HSV 转 Revit Color private static Color HsvToRgb(double h, double s, double v) { int hi = (int)(h * 6); double f = h * 6 - hi; byte p = (byte)(v * (1 - s) * 255); byte q = (byte)(v * (1 - f * s) * 255); byte t = (byte)(v * (1 - (1 - f) * s) * 255); byte vByte = (byte)(v * 255); switch (hi % 6) { case 0: return new Color(vByte, t, p); case 1: return new Color(q, vByte, p); case 2: return new Color(p, vByte, t); case 3: return new Color(p, q, vByte); case 4: return new Color(t, p, vByte); default: return new Color(vByte, p, q); } } } }