【问题标题】:Check button image检查按钮图像
【发布时间】:2014-02-03 23:15:28
【问题描述】:

我需要检查按钮是否没有图像(BackColor 变为绿色)或名为 Atorre 的图像(BackColor 变为红色),这是我的代码:

public static bool IsEnemyOrEmptyA(Button check)
{
    var Atorre = teste.Properties.Resources.Atorre;
    bool res;
    if (check == null || check.Image == null)
    {
        res = true;
        check.BackColor = Color.Green;
        return res;
    }
    else if (check.Image == teste.Properties.Resources.Atorre)
    {
        res = true;
        check.BackColor = Color.Red;
        return res;
    }
    else
    {
        res = false;
        return res;
    }
}

但即使是其他图像,按钮也会显示背景色为红色或不显示任何内容。 有什么建议吗?

【问题讨论】:

  • 我认为您可能需要包含更多代码才能使这个问题有意义。
  • 也许使用.Equals() 代替==
  • .Equals() 也不起作用。

标签: c# image button


【解决方案1】:

这是比较图像的唯一方法,您不应该比较图像,而是比较一些变量。

   private void button1_Click(object sender, EventArgs e)
    {
        var Atorre = Resource1.test;
        var DifferentImage = Resource1.test2;
        byte[] a = BitmapToBytes(Atorre);
        byte[] b = BitmapToBytes(DifferentImage);

        bool isEqual = true;

        if (a.Length == b.Length && a != null && b != null)
        {
            for (int i = 0; i < b.Length; i++)  //compare every byte
            {
                if (b[i] != a[i])
                {
                    isEqual = false;
                    break;
                }
            }
        }
        else
        {
            isEqual = false;
        }

        if(isEqual)
            MessageBox.Show("It's EQUAL");
        else
            MessageBox.Show("Not EQUAL");

    }


    //Convert Image to Bytes 
    public static byte[] BitmapToBytes(Bitmap Bitmap)
    {
        System.IO.MemoryStream ms = null;
        try
        {
            ms = new System.IO.MemoryStream();
            Bitmap.Save(ms, Bitmap.RawFormat);
            byte[] byteImage = new Byte[ms.Length];
            byteImage = ms.ToArray();
            return byteImage;
        }
        catch (ArgumentNullException ex)
        {
            throw ex;
        }
        finally
        {
            ms.Close();
        }
    }

【讨论】:

  • 没问题,但是如果你有很多图片,你应该这样使用变量会很慢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
  • 2021-08-14
  • 1970-01-01
  • 2012-12-02
  • 2020-03-23
  • 1970-01-01
  • 2013-10-29
相关资源
最近更新 更多