WinForm ImageButton

        今天在作项目时,需要使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
    }
}

 
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值