【问题标题】:Get the Background Color of a Rectangle [duplicate]获取矩形的背景颜色 [重复]
【发布时间】:2014-05-26 13:40:42
【问题描述】:

我已经画了一个矩形:

Rectangle rectangle=new Rectangle(10,10,40,40);
g.FillRectangle(new SolidBrush(Color.Red),rectangle);

有人可以告诉我点击时是否可以获得矩形的背景颜色:

private void Form1_MouseClick(object sender, MouseEventArgs e)
{
            if (rectangle.Contains(e.Location))
            {
                //get the color here that it should be Red
                Console.WriteLine("COLOR IS: " ????);
            }
}

提前致谢

【问题讨论】:

  • 如果您在表单上绘制一个矩形,那么您需要在绘制事件中执行此操作,以便在表单重新绘制时重新绘制矩形。因此,您需要同时保留矩形和颜色,并且当您确定单击在矩形内时,您应该能够获得该颜色。如果你没有在绘制事件中绘制矩形,那么你就没有在窗体上绘制它,你已经在屏幕上恰好也绘制了窗体的地方绘制了它。

标签: c# drawrectangle


【解决方案1】:

看看这个answer

基本思想是获取触发点击事件的像素颜色 (e.Location),为此您可以使用 gdi32.dll 的 GetPixel 方法。

链接中的代码稍作修改:

class PixelColor
{
    [DllImport("gdi32")]
    public static extern uint GetPixel(IntPtr hDC, int XPos, int YPos);

    [DllImport("User32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr GetWindowDC(IntPtr hWnd);

    /// <summary> 
    /// Gets the System.Drawing.Color from under the given position. 
    /// </summary> 
    /// <returns>The color value.</returns> 
    public static Color Get(int x, int y)
    {
        IntPtr dc = GetWindowDC(IntPtr.Zero);

        long color = GetPixel(dc, x, y);
        Color cc = Color.FromArgb((int)color);
        return Color.FromArgb(cc.B, cc.G, cc.R);
    }
}

请注意,在调用函数之前,您可能需要将 X 和 Y 坐标转换为屏幕坐标。

但在您的情况下,真正的答案是:红色。 :)

【讨论】:

    猜你喜欢
    • 2013-01-21
    • 2016-07-11
    • 2015-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    • 2012-02-15
    • 2021-11-20
    相关资源
    最近更新 更多