游乐游手机版
首页/编程语言/文章详情

C#基于System.Drawing的位图取色与绘图实现

时间:2026-08-06 17:44
C 中利用System Drawing库,通过截屏获取屏幕指定点颜色(推荐)或调用WindowsAPI实现取色,并可在位图上使用DrawEllipse绘制抗锯齿圆形。结合鼠标交互,实现点击图片取色并在点击位置画圆标记,提供完整WindowsForms示例。

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

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方法中显式清理。养成良好的资源管理习惯,后续开发大型项目时才不会出现内存异常增长的问题。

来源:https://www.jb51.net/program/368574hde.htm
上一篇Go Time 新手入门教程 从零开始快速掌握编程技巧 下一篇RabbitMQ消息积压排查:从指标定位到消费者扩容
本站内容用于信息整理与展示,如有侵权或内容问题请及时联系处理。

相关推荐

补充同频道和同主题内容,方便继续浏览更多相关内容。

同类最新

继续查看同栏目最近更新的文章。

更多
35岁转行网络安全:从经验复用到实战落地的可行性评估
编程语言 · 2026-10-10

35岁转行网络安全:从经验复用到实战落地的可行性评估

35岁转行网络安全并非不可行,但核心在于将过往经验转化为安全领域的差异化优势。本文从岗位匹配度、技能学习顺序、实战验证闭环、求职策略及常见误区五个维度,提供一套可执行的转行评估框架与行动指南,帮助读者理性判断投入产出比,避开无效学习陷阱。

网络安全行业前景分析:技术演进与市场机遇
编程语言 · 2026-10-10

网络安全行业前景分析:技术演进与市场机遇

围绕2026年网络安全行业的发展变化,从市场需求、技术演进、细分赛道和企业落地四个层面展开,帮助读者理解行业增长逻辑、识别重点技术方向,并建立评估市场机遇与风险的基本框架。 OWASP China +2 IDC +2

2026网络安全求职全景:从岗位拆解到实战作品集构建
编程语言 · 2026-10-10

2026网络安全求职全景:从岗位拆解到实战作品集构建

本文基于2026年网络安全行业招聘趋势,深入剖析安全运维、攻防渗透、云安全等核心岗位的技术栈差异与能力侧重。文章不仅梳理了从基础网络知识到高级攻防演练的学习路径,更提供了“以终为始”的求职策略:通过拆解JD反向验证技能缺口,并指导如何将CTF经历、HomeLab实验转化为具有说服力的项目作品集,帮助

2024安全攻防实战:从勒索软件到AI治理的破局与重构
编程语言 · 2026-10-10

2024安全攻防实战:从勒索软件到AI治理的破局与重构

2024年的网络安全已从单纯的技术对抗演变为业务连续性的生死博弈。本文基于ENISA、微软及世界经济论坛的最新报告,深入剖析勒索软件的“双重勒索”演变、身份凭证成为首要攻击面的现状,以及生成式AI带来的攻防不对称性。文章进一步拆解企业如何从被动防御转向“发现-保护-检测-响应-恢复”的闭环体系,重点

网站编程AI工具测评:提升开发效率的辅助软件推荐
编程语言 · 2026-10-10

网站编程AI工具测评:提升开发效率的辅助软件推荐

围绕网站开发中的实际需求,对AI编程辅助工具进行分类、操作体验与效果验证,帮助读者快速判断哪些工具真正能提升开发效率,并避开代码质量、隐私、安全与过度依赖等常见问题。