在进行winform项目开发时,有时候会单独显示窗体,用于提醒或者数据展示。下面就详细介绍如何实现。效果如下:

方案描述
获取图片形状,然后使用OnPaint方法,重新绘制
知识点
BitMap
封装 GDI+ 位图,此位图由图形图像及其属性的像素数据组成。 Bitmap 是用于处理由像素数据定义的图像的对象。
- 构造函数:Bitmap(Image)
从指定的现有图像初始化 Bitmap 类的新实例。 - 方法:MakeTransparent(Color)
使此 Bitmap的指定颜色透明。
csharp
Bitmap bit;//声明一个bitmap位图对象
private void Form1_Load(object sender, EventArgs e)
{
bit = new Bitmap(@"D:\\码云\\C#\\程序案例\\035-ImageNavigationForm\\resources\\bccd.png");
bit.MakeTransparent(Color.Blue);
}
OnPaint
OnPaint 是 Windows 窗体(WinForms)中用于自定义绘制控件外观的关键方法。当控件需要重绘(如首次显示、被遮挡后恢复、调用 Invalidate() 时),系统会自动触发该方法。
- 主要区别Paint事件:
1.OnPaint方法是对一个控件来说的;而Paint事件是对一个控件对象来说的。它们中前者相当于是类的一个成员函数,而后者相当于是类的一个函数指针类型的变量(会因对象的不同而不同)。
2.OnPaint方法引发Paint事件,所以重写OnPaint方法,一定要调用base.OnPaint,否则就不会引发Paint事件了。
csharp
Bitmap bit;//声明一个bitmap位图对象
private void Form1_Load(object sender, EventArgs e)
{
bit = new Bitmap(@"D:\\码云\\C#\\程序案例\\035-ImageNavigationForm\\resources\\bccd.png");
bit.MakeTransparent(Color.Blue);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if(bit !=null)
{
e.Graphics.DrawImage((Image)bit, new Point(0, 0));
}
}
代码展示
csharp
public partial class Form1 : Form
{
Bitmap bit;//声明一个bitmap位图对象
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
bit = new Bitmap(@"D:\\码云\\C#\\程序案例\\035-ImageNavigationForm\\resources\\bccd.png");
bit.MakeTransparent(Color.Blue);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if(bit !=null)
{
e.Graphics.DrawImage((Image)bit, new Point(0, 0));
}
}
private void label1_Click(object sender, EventArgs e)
{
this.Close();
}
}