我通过继承Button类进行改写组件,组件中的代码如下,为什么生成的新的Button不正常(我只是想Button的BackgroundImage设置为一个渐变的画片),而且按钮的名字不是txButton开头。
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Drawing;namespace WindowsApplication1
{
    public partial class TXButton :Button 
    {
        public TXButton()
        {
            
        }        protected override void OnPaint(PaintEventArgs pevent)
        {
            base.OnPaint(pevent);            LinearGradientBrush gradBrush;
            gradBrush = new LinearGradientBrush(this.ClientRectangle, Color.LightCoral, Color.Blue, LinearGradientMode.ForwardDiagonal);            Bitmap bmp = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height);            Graphics g = Graphics.FromImage(bmp);            g.FillRectangle(gradBrush, new Rectangle(0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height));
            base.BackgroundImage = bmp;
            base.BackgroundImageLayout = ImageLayout.Center;
            gradBrush.Dispose();
            this.UpdateStyles();
        }
    }
}谢谢

解决方案 »

  1.   

    不知道不正常在那里,不过可以给个建议。如果你用背景图片的话,不要在OnPaint里面做。OnPaint会被运行很多次,而创建Bitmap比较耗资源。
    你可以在OnSizeChanged里面做,只有按钮的大小变了才重新生成新的背景图片:
    public partial class TXButton : Button
    {
        public TXButton()
        {
        }    protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);        LinearGradientBrush gradBrush;
            gradBrush = new LinearGradientBrush(this.ClientRectangle, Color.LightCoral, Color.PeachPuff, LinearGradientMode.ForwardDiagonal);
            Bitmap bmp = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height);
            
            using(gradBrush)
            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.FillRectangle(gradBrush, this.ClientRectangle);
            }
            base.BackgroundImage = bmp;
        }
    }
      

  2.   

    自己把渐变的图片直接画上去就是了,还搞个什么BackgroundImage,不嫌麻烦