今天在作项目时,需要使Button使用图片作背景,但是在不规则的图片下,按钮也要有不同的显示,因此自己写了个按钮来实现。
其实非常简单,我查了Button的实现,发现它继承了ButtonBase, IButtonControl类,而我也想实现这两个类,但是十分麻烦,于是就简单一些,直接继承了Button类,重载了他的OnPaint方法。因此,一个ImageButton就完成了。他可以根据按钮的大小自动调接图片,使图片始终处于Stretch状态,并且Button的文字始终居中。
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace ImageButton
{
public partial class ImageButton : Button
{
#region Constructor
/// <summary>
/// Constructor
/// </summary>
public ImageButton()
{
InitializeComponent();
}
#endregion
#region 重载OnPaint方法
/// <summary>
/// 重载OnPaint方法
/// </summary>
/// <param name="pevent"></param>
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
if (BackgroundImage != null)
{
Image img = this.BackgroundImage;
g.DrawImage(img, e.ClipRectangle, 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
}
g.DrawString(Text, Font, new SolidBrush(Color.Black), e.ClipRectangle, sf);
}
#endregion
}
}
其实非常简单,我查了Button的实现,发现它继承了ButtonBase, IButtonControl类,而我也想实现这两个类,但是十分麻烦,于是就简单一些,直接继承了Button类,重载了他的OnPaint方法。因此,一个ImageButton就完成了。他可以根据按钮的大小自动调接图片,使图片始终处于Stretch状态,并且Button的文字始终居中。
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace ImageButton
{
public partial class ImageButton : Button
{
#region Constructor
/// <summary>
/// Constructor
/// </summary>
public ImageButton()
{
InitializeComponent();
}
#endregion
#region 重载OnPaint方法
/// <summary>
/// 重载OnPaint方法
/// </summary>
/// <param name="pevent"></param>
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
if (BackgroundImage != null)
{
Image img = this.BackgroundImage;
g.DrawImage(img, e.ClipRectangle, 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
}
g.DrawString(Text, Font, new SolidBrush(Color.Black), e.ClipRectangle, sf);
}
#endregion
}
}