我想为游戏编写类似控制台的gui,然后从一个真正的控制台开始。所以我有一个类,指定了颜色。现在我想将consolecolor转换为rgb(24位),反之亦然。我已经试过了:
int d = (((int)col & 8) != 0) ? 255 : 128;
r = (((int)col & 4) != 0) ? d : 0;
g = (((int)col & 2) != 0) ? d : 0;
b = (((int)col & 1) != 0) ? d : 0;
4位色具有这种位外观:drgb。当d为0时,颜色将为深色,如果为1,则rgb值为255。我的问题是:在程序中,颜色1000(亮黑色)和颜色0111(深白色)是黑色和灰色。它们应该是深灰色和浅灰色。以及如何通过四舍五入将颜色转换回去,而不仅仅是将特定颜色转换回去?
颜色是在具有三个坐标轴R,G和B的3维参数空间中定义的。您可以计算两种颜色之间的距离a
,b
如下所示:
double dist = Math.Sqrt(Sqr(a.R - b.R) + Sqr(a.G - b.G) + Sqr(a.B - b.B));
此公式使用此方法
private static int Sqr(int x)
{
return x * x;
}
最佳匹配的颜色是距离最小的颜色。您还可以使用距离的平方来比较距离(以提高效率):
int sqrDist = Sqr(a.R - b.R) + Sqr(a.G - b.G) + Sqr(a.B - b.B);
现在使用16种控制台颜色定义一个数组:
Color[] consoleColors = new[] {
Colors.Black,
Colors.Red,
...
};
并获得最佳搭配
Color bestMatch;
int bestSqrDist = Int32.MaxValue;
foreach (Color consoleColor in consoleColors) {
int sqrDist = Sqr(theColor.R - consoleColor.R) +
Sqr(theColor.G - consoleColor.G) +
Sqr(theColor.B - consoleColor.B);
if (sqrDist < bestSqrDist) {
bestMatch = consoleColor;
bestSqrDist = sqrDist;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句