![](/img/trans.png)
[英]C# Convert System.ConsoleColor to System.Drawing.Color
[英]C# Convert 4 bit color (=ConsoleColor) to RGB and back
我想為游戲編寫類似控制台的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(深白色)是黑色和灰色。 它們應該是深灰色和淺灰色。 以及如何通過四舍五入將顏色轉換回去,而不僅僅是將特定顏色轉換回去?
淺灰色是一種特殊情況,您只需要單獨處理即可。
您可以使用顏色的RGB值設置陣列並將其用於轉換,當您要轉換顏色時,它們將非常方便。
將24位顏色轉換為16種顏色的調色板可以通過許多不同的方式完成。 一種方法是計算RGB顏色和調色板顏色之間的差異,並選擇差異最小的顏色:
例:
byte[] r = { 0, 0, 0, 0, 128, 128, 128, 128, 192, 0, 0, 0, 255, 255, 255, 255 };
byte[] g = { 0, 0, 128, 128, 0, 0, 128, 128, 192, 0, 255, 255, 0, 0, 255, 255 };
byte[] b = { 0, 128, 0, 128, 0, 128, 0, 128, 192, 255, 0, 255, 0, 255, 0, 255 };
Color c = Color.Khaki;
int index = Enumerable.Range(0, 16)
.OrderBy(i => Math.Abs(c.R - r[i]) + Math.Abs(c.G - g[i]) + Math.Abs(c.B - b[i]))
.First();
顏色是在具有三個坐標軸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;
}
}
我不確定我是否正確理解您,但是請嘗試以下操作:
int d = (((int)col & 8) != 0) ? 64 : 0;
r = (((int)col & 4) != 0) ? d + 191 : d;
g = (((int)col & 2) != 0) ? d + 191 : d;
b = (((int)col & 1) != 0) ? d + 191 : d;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.