gpt4 book ai didi

c# - Color.GetPixel().equals(Color.Blue) 的结果为假

转载 作者:行者123 更新时间:2023-11-30 20:44:44 32 4
gpt4 key购买 nike

Color c1 = image.GetPixel (7, 400);
Color c2 = Color.Blue;
Console.WriteLine (image.GetPixel (7, 400));
Console.WriteLine (Color.Blue);
Console.WriteLine (c1.Equals(c2));

控制台输出:

Color [A=255, R=0, G=0, B=255]
Color [Blue]
False

我是 C# 的新手,我不知道为什么会返回 false。谁能告诉我为什么这不起作用?

我正尝试在这种情况下使用它。

for (int i = 0; i < image.Height; i++)  //loop through rows
{
for (int j = 0; j < image.Width; j++) //loop through columns
{
//Console.WriteLine ("i = " + i);
//Console.WriteLine ("j = " + j);
if ((image.GetPixel (i, j)) == Color.Blue)
{
return new Tuple<int, int>(i,j);
}

if (i == image.Height-1 && j == image.Width-1)
{
Console.WriteLine ("Image provided does not have a starting point. \n" +
"Starting points should be marked by Blue.");
Environment.Exit (0);
}
}
}

最佳答案

正如您已经注意到的,以下示例将返回 false:

Bitmap bmp = new Bitmap(1, 1);
bmp.SetPixel(0, 0, Color.Blue);
Color c1 = bmp.GetPixel(0, 0);
Console.WriteLine("GetPixel:" + c1);
Console.WriteLine("Color:" + Color.Blue);
Console.WriteLine("Equal?:" + c1.Equals(Color.Blue));

Console.ReadLine();

原因有点难以理解:

如果你查看Bitmap-Class的源代码,你会发现

public Color GetPixel(int x, int y) { 
//lot of other code
return Color.FromArgb(color);
}

http://reflector.webtropy.com/default.aspx/DotNET/DotNET/8@0/untmp/whidbey/REDBITS/ndp/fx/src/CommonUI/System/Drawing/Bitmap@cs/1/Bitmap@cs

Color.Equals() 的文档说:

To compare colors based solely on their ARGB values, you should use the ToArgb method. This is because the Equals and Equality members determine equivalency using more than just the ARGB value of the colors. For example, Black and FromArgb(0,0,0) are not considered equal, since Black is a named color and FromArgb(0,0,0) is not.

https://msdn.microsoft.com/en-us/library/e03x8ct2(v=vs.110).aspx

因此,返回的 Color 不等于 Color.Blue - 即使就 ARGB 值而言它是 Color.Blue

要绕过这个,使用:

Console.WriteLine("Equal?:" + c1.ToArgb().Equals(Color.Blue.ToArgb()));

作为示例的最后一行。

关于c# - Color.GetPixel().equals(Color.Blue) 的结果为假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28920332/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com