How to check if image object is the same as one from resource?

后端 未结 3 2110
星月不相逢
星月不相逢 2020-11-29 13:19

So I\'m trying to create a simple program that just change the picture in a picture box when it\'s clicked. I\'m using just two pictures at the moment so my code for the pic

3条回答
  •  感动是毒
    2020-11-29 13:58

         if (pictureBox1.Image == Labirint.Properties.Resources.first)
    

    There's a trap here that not enough .NET programmers are aware of. Responsible for a lot of programs that run with bloated memory footprints. Using the Labirint.Properties.Resources.xxxx property creates a new image object, it will never match any other image. You need to use the property only once, store the images in a field of your class. Roughly:

        private Image first;
        private Image reitmi;
    
        public Form1() {
            InitializeComponent();
            first = Labirint.Properties.Resources.first;
            reitmi = Labirint.Properties.Resources.reitmi;
            pictureBox1.Image = first;
        }
    

    And now you can compare them:

        private void pictureBox1_Click(object sender, EventArgs e) {
            if (pictureBox1.Image == first) pictureBox1.Image = reitmi;
            else pictureBox1.Image = first;
        }
    

    And to avoid the memory bloat:

        private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
           first.Dispose();
           reitmi.Dispose();
        }
    

提交回复
热议问题