c#造個輪子-取色器TakeColor(附源碼)
緣由
看過上篇文章《OpenCvSharp基于顏色反差規避FBA面單貼標(2)》的都應該有印象這么一行代碼:
// 面單顏色列表(十六進制格式)
privatestaticreadonly List<string> LabelColors = new List<string>
{
"#7C7C7C", "#707070", "#5E5E5E", "#8F8F8D", "#5F5F5F", "#CBCBC9","#FFFFFF","#FEFEFE","#FCFCFC" ,"#7B7B7B","#828282","#7D7D7D","#787878","#D7D7D5","#777777","#7F7F7F"
};
每次有不同顏色或者無法定位的面單,都需要人工補錄面單的背景色HEX,那么能不能集成一個工具,自動吸取圖片色號保存后,這里能立即生效呢?答案是肯定的!先看看動態效果圖:

-
點擊取色,跟隨鼠標實時顯示背景色便于定位
-
快捷鍵Alt+C,抓取當前鼠標所在背景色存儲到列表并存儲到根目錄colorHistory.json文件,便于其他地方讀取
-
列表支持右鍵刪除錯誤顏色(如下圖)
-
其他地方讀取抓取的顏色列表

保存的json文件格式如下:
[ "#018DBE", "#B1C681", "#03231E", "#61CB81", "#00424A", "#B5BD68", "#A3D9A3", "#F68A1E", "#0E83BA", "#861B2D", "#059BBC" ]
每次抓取都會往json存儲當前最新色號,然后其他地方實時讀取json即可:
//// 面單顏色列表(十六進制格式)
//private static readonly List<string> LabelColors = new List<string>
//{
// "#7C7C7C", "#707070", "#5E5E5E", "#8F8F8D", "#5F5F5F", "#CBCBC9","#FFFFFF","#FEFEFE","#FCFCFC" ,"#7B7B7B","#828282","#7D7D7D","#787878","#D7D7D5","#777777","#7F7F7F"
//};
static List<string> LabelColors = new List<string>();
privatestatic List<string> LoadColorList()
{
try
{
string historyFilePath = System.Windows.Forms.Application.StartupPath + @"\colorHistory.json";
if (File.Exists(historyFilePath))
{
string json = File.ReadAllText(historyFilePath);
var hexList = JsonSerializer.Deserialize<List<string>>(json);
foreach (var hex in hexList)
{
if (!string.IsNullOrEmpty(hex))
{
LabelColors.Add(hex);
}
}
return LabelColors;
}
}
catch (Exception ex)
{
MessageBox.Show($"加載歷史記錄失敗: {ex.Message}", "錯誤",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
returnnull;
}
![116076-20250310125032345-1793233350[1]](https://img2024.cnblogs.com/blog/116076/202509/116076-20250924180326264-1688793031.png)
private List<Color> colorHistory = new List<Color>(); private MagnifierForm magnifierForm; privatestring historyFilePath = "colorHistory.json"; private ContextMenuStrip historyContextMenu;
// 初始化右鍵菜單
privatevoidInitializeContextMenu()
{
historyContextMenu = new ContextMenuStrip();
ToolStripMenuItem deleteItem = new ToolStripMenuItem("刪除選中顏色");
deleteItem.Click += DeleteItem_Click;
ToolStripMenuItem clearAllItem = new ToolStripMenuItem("清空所有歷史");
clearAllItem.Click += ClearAllItem_Click;
ToolStripMenuItem copyItem = new ToolStripMenuItem("復制顏色值");
copyItem.Click += CopyItem_Click;
historyContextMenu.Items.AddRange(new ToolStripItem[] {
copyItem, deleteItem, clearAllItem
});
lstHistory.ContextMenuStrip = historyContextMenu;
LoadColorHistory();
// 設置ListBox為自繪模式
lstHistory.DrawMode = DrawMode.OwnerDrawFixed;
lstHistory.DrawItem += LstHistory_DrawItem;
}
ListBox實時顯示當前吸取的背景色,重繪代碼如下:
// 繪制ListBox項
privatevoidLstHistory_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index < 0 || e.Index >= colorHistory.Count) return;
e.DrawBackground();
Color color = colorHistory[e.Index];
string text = $"{ColorToHex(color)} - RGB({color.R},{color.G},{color.B})";
// 繪制顏色塊
Rectangle colorRect = new Rectangle(e.Bounds.Left + 2, e.Bounds.Top + 2, 20, e.Bounds.Height - 4);
using (SolidBrush brush = new SolidBrush(color))
{
e.Graphics.FillRectangle(brush, colorRect);
}
e.Graphics.DrawRectangle(Pens.Black, colorRect);
// 繪制文本
Rectangle textRect = new Rectangle(e.Bounds.Left + 25, e.Bounds.Top, e.Bounds.Width - 25, e.Bounds.Height);
using (SolidBrush textBrush = new SolidBrush(e.ForeColor))
{
e.Graphics.DrawString(text, e.Font, textBrush, textRect);
}
e.DrawFocusRectangle();
}
RGB和HEX 相互轉換
// HEX字符串轉Color
private Color HexToColor(string hex)
{
try
{
// 移除#號
hex = hex.Replace("#", "");
// 處理3位HEX
if (hex.Length == 3)
{
hex = $"{hex[0]}{hex[0]}{hex[1]}{hex[1]}{hex[2]}{hex[2]}";
}
// 處理6位HEX
if (hex.Length == 6)
{
byte r = Convert.ToByte(hex.Substring(0, 2), 16);
byte g = Convert.ToByte(hex.Substring(2, 2), 16);
byte b = Convert.ToByte(hex.Substring(4, 2), 16);
return Color.FromArgb(r, g, b);
}
return Color.Empty;
}
catch
{
return Color.Empty;
}
}
// 顏色轉HEX
privatestringColorToHex(Color color)
{
return$"#{color.R:X2}{color.G:X2}{color.B:X2}";
}
結束語
感謝各位耐心查閱! 如果您有更好的想法歡迎一起交流,有不懂的也可以微信公眾號聯系博主,作者公眾號會經常發一些實用的小工具和demo源碼,需要的可以去看看!另外,如果覺得本篇博文對您或者身邊朋友有幫助的,麻煩點個關注!贈人玫瑰,手留余香,您的支持就是我寫作最大的動力,感謝您的關注,期待和您一起探討!再會!(公眾號回復“takecolor”獲取完整代碼)
作者:Stephen-kzx
出處:http://www.rzrgm.cn/axing/
公眾號:會定時分享寫工作中或者生活中遇到的小游戲和小工具源碼。有興趣的幫忙點下關注!感恩!
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。

浙公網安備 33010602011771號