C# 中的循环按钮背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-01 08:49:32  来源:igfitidea点击:

Cycle Button Background Images in C#

提问by Justin Bennett

I have a form in C# that has a button that, when clicked, I want the background image to cycle through a set of images (which I have as resources to the project). The images are named '_1', '_2', etc. and each time I click the button I want its background image to increment to the next one and go back to "_1" when it gets to the highest. Is there a way to do this?

我有一个 C# 表单,它有一个按钮,单击该按钮时,我希望背景图像循环显示一组图像(我将这些图像作为项目的资源)。图像被命名为“_1”、“_2”等,每次我单击按钮时,我都希望它的背景图像增加到下一个,并在达到最高时返回“_1”。有没有办法做到这一点?

I tried getting button1.BackgroundImage.ToString()but that yields System.Drawing.Bitmapinstead of Resources._1like I was thinking it would (in which case I could just get the last character and switch on that to change the background to the appropriate new image).

我试过获取,button1.BackgroundImage.ToString()但结果System.Drawing.Bitmap不是Resources._1我想象的那样(在这种情况下,我可以获取最后一个字符并打开它以将背景更改为适当的新图像)。

Thanks for your help.

谢谢你的帮助。

采纳答案by Landon

Why don't you just put the images in an array?

你为什么不把图像放在一个数组中?

回答by Chris Farmer

You could subclass Button and override the BackgroundImage property so you can better keep track of the current resource that represents the image. You might also override the onclick method to internally handle cycling to the next image, though that might be a little weird if the resources are handled outside of your derived button class.

您可以子类化 Button 并覆盖 BackgroundImage 属性,以便更好地跟踪表示图像的当前资源。您还可以覆盖 onclick 方法以在内部处理循环到下一个图像,但如果资源是在派生按钮类之外处理的,这可能有点奇怪。

回答by zahir

class YourClass
{
    private IEnumerator<Image> enumerator;

    YourClass(IEnumerable<Image> images)
    {
        enumerator = (from i in Enumerable.Range(0, int.Max)
                      from image in images
                      select image).GetEnumerator();
        enumerator.MoveNext();
    }

    public Image CurrentImage { get { return enumerator.Current; } }

    public void OnButtonClick() { enumerator.MoveNext(); }
}

You can use this code as a backing class for your control under the assumption that user wont click the button more than two billion times.

假设用户不会单击按钮超过 20 亿次,您可以将此代码用作控件的支持类。

Just note that once this class is created you cannot modify given image list outside. If you want to do such things you need to implement disposable pattern and dispose the enumerator accordingly.

请注意,一旦创建了此类,您就无法在外部修改给定的图像列表。如果你想做这样的事情,你需要实现一次性模式并相应地处理枚举器。