0

我正在尝试将随机图像分配给面板:

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";
    }
}

但是我的代码会导致错误:

无法将类型“字符串”隐式转换为“System.Drawing.Image”

4

4 回答 4

3

用这个 :

Panel1.BackgroundImage = System.Drawing.Bitmap.FromFile(yourPath);
于 2013-03-27T09:30:23.720 回答
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)];

希望这可以帮助。

于 2013-03-27T09:32:27.100 回答
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");

            }
        }
于 2013-03-27T09:32:04.260 回答
0

截屏

在您的项目资源中添加图像,然后像这样使用它:

Panel1.BackgroundImage = Properties.Resources.MyImage;
于 2013-03-27T09:32:19.773 回答