我正在尝试将随机图像分配给面板:
System.Random randomNum = new System.Random();
int myInt = randomNum.Next(4);
if (Panel1.BackgroundImage != null)
{
switch (myInt)
{
case 0:
Panel1.BackgroundImage = @"C:\Users\etrit.bujupi\Desktop\IO-Etrit\CardGame\Images\2-Black.jpg";
}
}
但我的代码导致错误:
不能将'string'类型转换为'System.Drawing.Image'
答案 0 :(得分:3)
使用此:
Panel1.BackgroundImage = System.Drawing.Bitmap.FromFile(yourPath);
答案 1 :(得分:3)
此代码可能会帮助您:
ImageList images = new ImageList();
images.Images.Add(Image.FromFile("C:\\pic1.bmp"));
images.Images.Add(Image.FromFile("C:\\pic2.bmp"));
//Fill with more images
//Make a Random-object
Random rand = new Random();
// This could also be a panel already on the Form
Panel p = new Panel();
//Pick a random image from the list
p.BackgroundImage = images.Images[rand.Next(0, images.Images.Count - 1)];
希望这有帮助。
答案 2 :(得分:0)
System.Random randomNum = new System.Random();
int myInt = randomNum.Next(4);
if (Panel1.BackgroundImage != null)
{
switch (myInt)
{
case 0:
Panel1.BackgroundImage = System.Drawing.Bitmap.FromFile( @"C:\Users\etrit.bujupi\Desktop\IO-Etrit\CardGame\Images\2-Black.jpg");
}
}
答案 3 :(得分:0)
在项目资源中添加图像,然后使用它:
Panel1.BackgroundImage = Properties.Resources.MyImage;