如何使用ImageLocation将图像放入我的图片框?

Tho*_*mas 2 c# user-interface winforms

我在我的面板中创建了一个图片框,我想在本地填写图像.

这是我到目前为止所做的,以下代码只是我的面板创建代码的一小部分.

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17)
        };
        p.Controls.Add(picture);
        picture.ImageLocation = @"..\Image\1.jpg";
Run Code Online (Sandbox Code Playgroud)

它确实有效但不完全,因为在我启动了我的c#windows窗体应用程序之后,它显示了一个小的白色框,中间有一个红叉而不是图像.知道怎么解决吗?

Jef*_*ata 9

使用设置图像picture.ImageLocation()工作正常,但您使用的是相对路径.根据.exe构建后的位置检查路径.

例如,如果您.exe位于:

<project folder>/bin/Debug/app.exe

图像必须位于:

<project folder>/bin/Image/1.jpg


当然,您可以在设计时设置图像(属性表Image上的PictureBox属性).

如果必须在运行时设置它,确保知道图像位置的一种方法是将图像文件添加到项目中.例如,将新文件夹添加到项目中,为其命名Image.右键单击该文件夹,选择"添加现有项目"并浏览到您的图像(确保文件过滤器设置为显示图像文件).添加图像后,在属性表中设置Copy to Output DirectoryCopy if newer.

此时,在构建应用程序时将复制映像文件,您可以使用

picture.ImageLocation = @"Image\1.jpg"; 
Run Code Online (Sandbox Code Playgroud)