写一个窗体应用程序代码,按下按钮选择本地png图片导入并显示出来,图片透明部分可以看到后面的控件
时间: 2023-05-11 14:07:27 浏览: 103
以下是一个简单的窗体应用程序代码,可以实现按下按钮选择本地png图片导入并显示出来,图片透明部分可以看到后面的控件:
```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private PictureBox pictureBox1;
private Button button1;
private OpenFileDialog openFileDialog1;
public Form1()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.button1 = new System.Windows.Forms.Button();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.Location = new System.Drawing.Point(12, 12);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(300, 300);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 318);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 1;
this.button1.Text = "选择图片";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// openFileDialog1
//
this.openFileDialog1.FileName = "openFileDialog1";
this.openFileDialog1.Filter = "PNG文件|*.png";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(324, 353);
this.Controls.Add(this.button1);
this.Controls.Add(this.pictureBox1);
this.Name = "Form1";
this.Text = "窗体应用程序";
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Image image = Image.FromFile(openFileDialog1.FileName);
Bitmap bitmap = new Bitmap(image);
bitmap.MakeTransparent(Color.White);
pictureBox1.Image = bitmap;
}
}
}
}
```
这个程序中,我们使用了一个PictureBox控件来显示图片,使用一个Button控件来选择图片。当用户点击选择图片按钮时,我们弹出一个OpenFileDialog对话框,让用户选择一个PNG格式的图片文件。然后,我们将这个图片文件加载到一个Image对象中,再将它转换成一个Bitmap对象,并将它的白色部分设为透明。最后,我们将这个Bitmap对象赋给PictureBox控件的Image属性,从而显示出这个图片。