我通过继承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();
}
}
}谢谢
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();
}
}
}谢谢
你可以在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;
}
}