我正在尝试创建记忆益智游戏。我想在表单加载时随意将图像设置为按钮。但我无法实现它。
我正在尝试将随机数分配给表单中的20个按钮,并根据数字随机分配图像。
这就是我的尝试。
private void Form1_Load(object sender, EventArgs e)
{
Button button = new Button();
Random rnd = new Random();
int number = 0;
foreach (Control item in Controls)
{
number = rnd.Next(1, 20);
button.Name = number.ToString();
}
if (button.Name == 1.ToString() || button.Name == 2.ToString())
{
Icon myIcon = (Icon)Resources.ResourceManager.GetObject(
@"C:\Users\richa\Desktop\Goat.png");
button.Image = myIcon.ToBitmap();
}
}
我是否正确地在Button上设置图片?
答案 0 :(得分:2)
您应该有一个按钮数组,以及可以随机化的图像数组:
public void PutRandomImagesOnButtons(Button[] buttons, Bitmap[] images)
{
var rand = new Random();
foreach (var btn in buttons)
{
btn.BackgroundImage = images[rand.Next(images.Length)];
}
}
对于新手,我建议手动创建20个按钮,然后使用以下代码创建数组:
private Button[] _btns;
private void Form1_Load(object sender, EventArgs e)
{
this._btns = new Button[]
{
this.btn1, this.btn2, this.btn3, ...
};
}
应用相同的逻辑来获取图像数组,并在最后调用PutRandomImagesOnButtons(this._btns, this._images)
(或者在任何时候,真的)。
要获得更高级的阅读,请搜索动态创建和添加控件,并且不可避免地要考虑FlowLayoutPanel
,这有助于您安排动态控件。
https://msdn.microsoft.com/en-us/library/aa287574%28v=vs.71%29.aspx
http://visualcsharptutorials.com/windows-forms/dynamically-adding-controls
答案 1 :(得分:1)
然后您可以使用Tag
:
button.Tag = number.ToString();
和
Convert.ToInt32(button.Tag) == 1
修改强>
private void Form1_Load(object sender, EventArgs e)
{
Random rnd = new Random();
bool[] used = new bool[20];
int number = 0;
// if you have your buttons created in a container (groupbox for example)
foreach (var btn in container.Controls)
{
number = rnd.Next(1, 20);
while(used[number])
{
number = rnd.Next(1,20);
}
((Button)btn).Tag = number.ToString();
used[number] = true;
// add goat.png to your resources beforehand
// right click your project --> properties --> resources --> add resource --> add existing file --> select goat.png, and rename it to GoatImg
if (number == 1 || number == 2)
{
btn.Image = Properties.Resources.GoatImg;
}
}
}
答案 2 :(得分:-2)
你可以使用guid订购。
Dictionary<int, Guid> dic = new Dictionary<int, Guid>();
int i = 0;
while (i < 20)
{
dic.Add(i, Guid.NewGuid());
i++;
}
// Now order by the guid.
var newDic = dic.OrderByDescending(item => item.Value).ToDictionary(kvp => kvp.Value, kvp => kvp.Key);
int iSetter = 0;
foreach (Control item in Controls)
{
Button button = new Button();
int number = newDic.ElementAt(iSetter++).Value;
button.Name = number.ToString();
if (button.Name == 1.ToString() || button.Name == 2.ToString())
{
Icon myIcon = (Icon)Resources.ResourceManager.GetObject(@"C:\Users\richa\Desktop\Goat.png");
button.Image = myIcon.ToBitmap();
}
Controls.Add(button);
}