简体   繁体   English

如何在C#中从资源文件中设置面板的背景图像?

[英]How to set the background image of a panel from a resource file in C#?

I want to change the background image of a panel in a C# Windows Forms application. 我想在C# Windows窗体应用程序中更改面板的背景图像。 The image I want to set as the background is located in a resource folder in Solution Explorer . 我想要设置为背景的图像位于解决方案资源管理器中的资源文件夹中。 How do I use it in code? 我如何在代码中使用它?

I tried this: 我试过这个:

panel1.BackgroundImage = Properties.Resources.Chalkboard; 

But it didn't work. 但它没有用。

I tried the same code like you did, and it works fine when I hit a button. 我像你一样尝试了相同的代码,当我按下按钮时它工作正常。

private void pnlBgBtn_Click(object sender, EventArgs e)
{
    panel1.BackgroundImage = Properties.Resources.image;
}

The name 'image' in 'Properties.Resources.image' should be the name you gave to the image. 'Properties.Resources.image'中的名称'image'应该是您为图像指定的名称。 The right name of the image should be the name shown in your project properties under project-proje. 图像的正确名称应该是project-proje下项目属性中显示的名称。

properties.Resources类不会将每个资源作为图像返回,因此您必须像这样将图像应用于图像

panel1.BackgroundImage = (Image)(Properties.Resourses.Chalkboard);

You can try this out: 你可以尝试一下:

 Bitmap bmp = new Bitmap(System.Reflection.Assembly.GetEntryAssembly().
    GetManifestResourceStream("MyProject.Resources.myimage.png"));

 panel1.BackgroundImage = bmp;

If you want to set the background image of a panel on page load then you have to write this code: 如果要在页面加载时设置面板的背景图像,则必须编写以下代码:

private void panel1_Paint(object sender, PaintEventArgs e)
{
    Assembly asm = Assembly.GetExecutingAssembly();
    Bitmap backgroundImage = new Bitmap(asm.GetManifestResourceStream("Image913.jpg"));

    e.Graphics.DrawImage(
        backgroundImage, 
        this.ClientRectangle,
        new Rectangle(0, 0, backgroundImage.Width, backgroundImage.Height),
        GraphicsUnit.Pixel);
}

If you want set the image except the panel, load use this code: 如果要设置除面板之外的图像,请使用以下代码加载:

Bitmap bmp = new Bitmap(System.Reflection.Assembly.GetEntryAssembly().
GetManifestResourceStream("MyProject.Resources.photo0018.jpg.png"));

panel1.BackgroundImage = bmp;

You can create an icon resource in Properties project folder. 您可以在“属性”项目文件夹中创建图标资源。 When you opened Properties click on Resources.resx and there Add Resource->Add New Icon menu items. 当您打开属性时,单击Resources.resx并在那里添加资源 - >添加新图标菜单项。 This will create an icon. 这将创建一个图标。 You can also load an icon from an existing file into the resource, in this case the icon will be built in your executable. 您还可以将现有文件中的图标加载到资源中,在这种情况下,图标将构建在可执行文件中。 So, when your icon added as a resource it will be given some name. 因此,当您的图标作为资源添加时,它将被赋予一些名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM