在C#开发中,利用System.Drawing命名空间处理位图、实现屏幕取色与绘图操作,其实比想象中更为简便。通过几行核心代码,即可轻松捕获屏幕上任意像素的颜色,或在图片上绘制圆形标记。本文将详细拆解关键方法,并提供一个完整的交互示例,帮助开发者快速上手实践。

1. 提取鼠标指定点的颜色值
要获取屏幕上任意位置的颜色值,最直接的方式是截取屏幕区域,然后从生成的位图中读取像素信息。本文将介绍两种实现方案:第一种基于Graphics.CopyFromScreen方法,通用性更强且更安全;第二种通过调用Windows API实现,速度更快但需要引入外部库。在实际项目开发中,推荐优先使用第一种方案。
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class ColorPicker
{
// 方法一:通过截屏获取指定屏幕坐标的颜色(推荐,更通用)
public static Color GetColorAtScreenPoint(Point screenPoint)
{
// 创建一个1x1像素的位图
using (Bitmap bitmap = new Bitmap(1, 1))
{
// 使用Graphics对象从屏幕指定位置拷贝1个像素 using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(screenPoint, Point.Empty, new Size(1, 1));
}
// 返回该像素的颜色
return bitmap.GetPixel(0, 0);
}
}
// 方法二:使用Windows API (GetPixel) 直接获取(需要引用user32.dll和gdi32.dll)
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll")]
private static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);
[DllImport("gdi32.dll")]
private static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);
public static Color GetColorAtScreenPoint_API(Point screenPoint)
{
IntPtr hdc = GetDC(IntPtr.Zero);
uint pixel = GetPixel(hdc, screenPoint.X, screenPoint.Y);
ReleaseDC(IntPtr.Zero, hdc);
// 将GetPixel返回的COLORREF转换为Color对象 byte red = (byte)(pixel & 0x000000FF);
byte green = (byte)((pixel & 0x0000FF00) >> 8);
byte blue = (byte)((pixel & 0x00FF0000) >> 16);
return Color.FromArgb(red, green, blue);
}
// 示例:在定时器或循环中实时获取鼠标位置颜色 public static void StartRealTimeColorPick(Label colorLabel)
{
Timer timer = new Timer();
timer.Interval = 50; // 每50毫秒更新一次
timer.Tick += (sender, e) =>
{
Point mousePos = Control.MousePosition;
Color color = GetColorAtScreenPoint(mousePos);
colorLabel.Text = $"坐标:({mousePos.X},{mousePos.Y}), RGB:({color.R},{color.G},{color.B})";
colorLabel.BackColor = color;
};
timer.Start();
}
}
方法一的核心逻辑仅需四步:创建一个1x1像素的Bitmap,通过Graphics对象从屏幕指定位置拷贝像素,调用GetPixel读取颜色值。方法二则采用GetDC与GetPixel的API路线,虽然无需生成临时位图,但需要手动释放设备上下文,稍有不慎可能导致内存泄漏。因此,日常开发中建议优先使用方法一。
2. 在位图上画圆
绘图操作离不开Graphics对象。只要从位图创建出Graphics画布,即可在上面绘制各种图形。下面提供两个方法:一个是在现有位图上绘制圆形,另一个是新建位图并直接画圆——开发者可根据实际需求灵活选用。
using System.Drawing;
using System.Drawing.Drawing2D;
public class BitmapDrawer
{
// 方法:在现有位图上绘制一个圆
public static Bitmap DrawCircleOnBitmap(Bitmap originalBitmap, Point center, int radius, Color circleColor, int penWidth = 2)
{
// 创建原图的副本,避免修改原图 Bitmap resultBitmap = new Bitmap(originalBitmap);
using (Graphics g = Graphics.FromImage(resultBitmap))
{
// 设置绘图质量
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// 创建画笔
using (Pen pen = new Pen(circleColor, penWidth))
{
// 计算圆的左上角坐标和直径 Rectangle rect = new Rectangle(center.X - radius, center.Y - radius, radius * 2, radius * 2);
// 绘制圆 g.DrawEllipse(pen, rect);
// 如果需要填充圆,使用 Brush
// using (SolidBrush brush = new SolidBrush(Color.FromArgb(50, circleColor)))
// {
// g.FillEllipse(brush, rect);
// }
}
}
return resultBitmap;
}
// 方法:创建一个新的位图并在上面画圆
public static Bitmap CreateBitmapWithCircle(int width, int height, Point center, int radius, Color backgroundColor, Color circleColor)
{
Bitmap bitmap = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(bitmap))
{
// 填充背景色 using (SolidBrush backgroundBrush = new SolidBrush(backgroundColor))
{
g.FillRectangle(backgroundBrush, 0, 0, width, height);
}
// 画圆
using (Pen pen = new Pen(circleColor, 3))
{
Rectangle rect = new Rectangle(center.X - radius, center.Y - radius, radius * 2, radius * 2);
g.DrawEllipse(pen, rect);
}
}
return bitmap;
}
}
需要特别说明的是,这里使用DrawEllipse绘制圆形,本质上是绘制一个外接矩形为正方形的椭圆。圆的半径即为正方形边长的一半。此外,务必开启抗锯齿开关SmoothingMode.AntiAlias,否则绘制出的圆形边缘会出现锯齿,影响效果的专业性。
3. 结合鼠标交互:点击取色并画圆
将上述两个功能整合起来,即可打造一个完整的交互工具:鼠标点击图片上的任意位置,立即获取该点的颜色值,同时在点击处绘制一个圆形作为标记。下面这个Windows Forms示例将所有这些功能集成在一起,代码中附有详细注释,可直接拷贝使用。
using System;
using System.Drawing;
using System.Windows.Forms;
namespace BitmapSimpleDemo
{
public partial class MainForm : Form
{
private Bitmap originalBitmap; // 原始位图 private Bitmap displayedBitmap; // 当前显示的位图(可能已画圆)
private Point lastClickPoint;
private int circleRadius = 30;
public MainForm()
{
InitializeComponent();
// 加载一张示例图片到PictureBox
originalBitmap = new Bitmap(@"你的图片路径.jpg");
pictureBox1.Image = originalBitmap;
displayedBitmap = (Bitmap)originalBitmap.Clone();
}
// PictureBox的鼠标点击事件 private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
if (originalBitmap == null) return;
lastClickPoint = e.Location;
// 1. 获取点击位置的颜色
Color clickedColor = originalBitmap.GetPixel(e.X, e.Y);
lblColorInfo.Text = $"点击点颜色 - R:{clickedColor.R} G:{clickedColor.G} B:{clickedColor.B}";
pnlColorPreview.BackColor = clickedColor;
// 2. 在 displayedBitmap 上以点击点为中心画圆
// 先重置为原图
displayedBitmap?.Dispose();
displayedBitmap = (Bitmap)originalBitmap.Clone();
using (Graphics g = Graphics.FromImage(displayedBitmap))
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
// 使用与取色形成对比的颜色画圆,例如取反色 Color drawColor = Color.FromArgb(255 - clickedColor.R, 255 - clickedColor.G, 255 - clickedColor.B);
using (Pen pen = new Pen(drawColor, 3))
{
Rectangle rect = new Rectangle(e.X - circleRadius, e.Y - circleRadius, circleRadius * 2, circleRadius * 2);
g.DrawEllipse(pen, rect);
}
}
// 3. 更新PictureBox显示 pictureBox1.Image = displayedBitmap;
}
// 按钮:保存画了圆的图片 private void btnSa ve_Click(object sender, EventArgs e)
{
if (displayedBitmap != null)
{
Sa veFileDialog sfd = new Sa veFileDialog();
sfd.Filter = "PNG Image|*.png|JPEG Image|*.jpg";
if (sfd.ShowDialog() == DialogResult.OK)
{
displayedBitmap.Sa ve(sfd.FileName);
}
}
}
// 按钮:重置图片,清除所有圆圈 private void btnReset_Click(object sender, EventArgs e)
{
displayedBitmap?.Dispose();
displayedBitmap = (Bitmap)originalBitmap.Clone();
pictureBox1.Image = displayedBitmap;
lblColorInfo.Text = "颜色信息";
pnlColorPreview.BackColor = SystemColors.Control;
}
// 窗体关闭时释放资源
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
originalBitmap?.Dispose();
displayedBitmap?.Dispose();
}
}
}
这个示例中有一个值得关注的细节:每次点击画圆前,都会先将displayedBitmap重置为原图的副本,从而避免多个圆圈叠加。如果希望保留历史标记,则无需重置,直接在displayedBitmap上继续绘制即可。此外,画圆的颜色采用了取反色策略,无论点击到哪种颜色,都能确保绘制的圆圈清晰可见。
关键操作总结:
| 任务 | 核心类/方法 | 说明 |
|---|---|---|
| 获取屏幕坐标颜色 | Graphics.CopyFromScreen | 通过截取1像素屏幕区域实现,无需API声明,更安全 。 |
| 获取位图像素颜色 | Bitmap.GetPixel(x, y) | 直接从Bitmap对象中读取指定坐标的颜色。 |
| 在位图上绘图 | Graphics.FromImage(bitmap) | 从位图创建Graphics画布,然后使用DrawEllipse画圆 。 |
| 鼠标交互取色 | PictureBox.MouseClick事件 + e.Location | 在控件内获取鼠标相对坐标,再对应到位图像素。 |
| 资源管理 | using语句或手动Dispose() | Bitmap和Graphics是非托管资源,使用后必须释放。 |
最后再强调一点:Bitmap和Graphics均属于非托管资源,使用完毕后务必及时释放,建议通过using语句包裹,或在Dispose方法中显式清理。养成良好的资源管理习惯,后续开发大型项目时才不会出现内存异常增长的问题。
