C# 将图像显示为 Windows 窗体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19193745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display an image into windows forms
提问by Kaoru
I wanted to display an image to the windows forms, but i already did this and the image did not come out.
我想向窗体显示图像,但我已经这样做了,但图像没有出来。
Where did I go wrong?
我哪里做错了?
Here is the code:
这是代码:
private void Images(object sender, EventArgs e)
{
PictureBox pb1 = new PictureBox();
pb1.Image = Image.FromFile("../SamuderaJayaMotor.png");
pb1.Location = new Point(100, 100);
pb1.Size = new Size(500, 500);
this.Controls.Add(pb1);
}
回答by dotNET
There could be many reasons for this. A few that come up quickly to my mind:
这可能有很多原因。一些我很快想到的:
- Did you call this routine AFTER
InitializeComponent()
? - Is the path syntax you are using correct? Does it work if you try it in the debugger? Try using backslash (\) instead of Slash (/) and see.
- This may be due to side-effects of some other code in your form. Try using the same code in a blank Form (with just the constructor and this function) and check.
- 你在 AFTER 之后调用了这个程序
InitializeComponent()
吗? - 您使用的路径语法是否正确?如果您在调试器中尝试它是否有效?尝试使用反斜杠 (\) 而不是斜杠 (/) 并查看。
- 这可能是由于表单中其他一些代码的副作用造成的。尝试在空白表单中使用相同的代码(只有构造函数和这个函数)并检查。
回答by Winner Crespo
Here (http://www.dotnetperls.com/picturebox) there 3 ways to do this:
在这里(http://www.dotnetperls.com/picturebox)有 3 种方法可以做到这一点:
- Like you are doing.
Using ImageLocation property of the PictureBox like:
private void Form1_Load(object sender, EventArgs e) { PictureBox pb1 = new PictureBox(); pb1.ImageLocation = "../SamuderaJayaMotor.png"; pb1.SizeMode = PictureBoxSizeMode.AutoSize; }
Using an image from the web like:
private void Form1_Load(object sender, EventArgs e) { PictureBox pb1 = new PictureBox(); pb1.ImageLocation = "http://www.dotnetperls.com/favicon.ico"; pb1.SizeMode = PictureBoxSizeMode.AutoSize; }
- 就像你在做的那样。
使用 PictureBox 的 ImageLocation 属性,例如:
private void Form1_Load(object sender, EventArgs e) { PictureBox pb1 = new PictureBox(); pb1.ImageLocation = "../SamuderaJayaMotor.png"; pb1.SizeMode = PictureBoxSizeMode.AutoSize; }
使用来自网络的图像,例如:
private void Form1_Load(object sender, EventArgs e) { PictureBox pb1 = new PictureBox(); pb1.ImageLocation = "http://www.dotnetperls.com/favicon.ico"; pb1.SizeMode = PictureBoxSizeMode.AutoSize; }
And please, be sure that "../SamuderaJayaMotor.png" is the correct path of the image that you are using.
请确保“../SamuderaJayaMotor.png”是您正在使用的图像的正确路径。
回答by Iliyan
I display images in windows forms when I put it in Load event like this:
当我把它放在 Load 事件中时,我以 Windows 窗体显示图像,如下所示:
private void Form1_Load( object sender , EventArgs e )
{
pictureBox1.ImageLocation = "./image.png"; //path to image
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
}