c# - 在实例中获取像素颜色

标签 c# .net graphics pixel

我在搜索这个网站上的帖子时发现了这个: How do I get the colour of a pixel at X,Y using c#?

这种方法对于尝试获取表单内部像素的颜色是否仍然有效?

如果不是,有什么方法可以从根本上“映射”二维颜色值数组中的表单?

例如,我有一个 Tron 游戏,我想检查轻型摩托车的下一个位置是否已经包含另一辆轻型摩托车。

谢谢, 伊恩

最佳答案

using System;
using System.Drawing;
using System.Runtime.InteropServices;

sealed class Win32
{
    [DllImport("user32.dll")]
    static extern IntPtr GetDC(IntPtr hwnd);

    [DllImport("user32.dll")]
    static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);

    [DllImport("gdi32.dll")]
    static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);

    static public System.Drawing.Color GetPixelColor(int x, int y)
    {
       IntPtr hdc = GetDC(IntPtr.Zero);
       uint pixel = GetPixel(hdc, x, y);
       ReleaseDC(IntPtr.Zero, hdc);
       Color color = Color.FromArgb((int)(pixel & 0x000000FF),
                    (int)(pixel & 0x0000FF00) >> 8,
                    (int)(pixel & 0x00FF0000) >> 16);
       return color;
    }
}

使用它,您可以执行以下操作:

public static class ControlExts
{
    public static Color GetPixelColor(this Control c, int x, int y)
    {
        var screenCoords = c.PointToScreen(new Point(x, y));
        return Win32.GetPixelColor(screenCoords.X, screenCoords.Y);
    }
}

因此,在您的情况下,您可以:

var desiredColor = myForm.GetPixelColor(10,10);

关于c# - 在实例中获取像素颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10135290/

相关文章:

c# - 适配器设计模式需要什么?

c# - 服务器不接受在 HttpClientHandler 上设置的证书

Android渐变图形质量(缩放位图)

c# - 使用 application/octet-stream 进行 POST 调用

c# - 如果 .NET Task.Run 用于运行 CPU 密集型任务,那么启动 IO 密集型任务在后台运行的正确方法是什么?

c# - 为什么我无法使用 SqlCommand 创建触发器?

c# - 如何在发送到浏览器之前获取 HTML

c# - 我在构建我的 C# 项目时遇到 "defined in an assembly that is not referenced"错误,如何解决?

image - SVG 对于网络上高度复杂的插图是否实用?

javascript - 同一 html 页面中具有不同数据的重复图表/图形