winform 自定义控件-按钮

来源:互联网 发布:长沙理工大学教务网络 编辑:程序博客网 时间:2024/05/16 23:35

winform 自定义按钮的实现

按钮效果图如下所示。

 

 

    通过颜色渐变渲染,让控件产生立体效果,上述的按钮就是通过线性渐变画刷二次渐变填充出来的。

    详看代码,后面有时间再加入类似win7计算器的淡入淡出效果。

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Drawing;

using System.Data;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Drawing.Drawing2D;

using System.Drawing.Text;

 

namespace RogerBar

{

    [ToolboxItem(true)]

    public partial class BottonEx : Button

    {

        #region Constructor

        public BottonEx()

        {

            SetStyle(ControlStyles.SupportsTransparentBackColor, true);

            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);

            SetStyle(ControlStyles.AllPaintingInWmPaint, true);

            SetStyle(ControlStyles.ResizeRedraw, true);

            SetStyle(ControlStyles.UserPaint, true);

            this.BackColor = Color.Transparent;

            this.FlatAppearance.BorderSize = 0;

            this.FlatStyle = FlatStyle.Flat;

            InitializeComponent();

        }

        #endregion

 

        #region Private

 

        //按钮状态

        enum ButtonState

        {

            //正常

            Normal,

            //鼠标进入

            Hover,

            //鼠标按下

            Pressed

        };

        private ButtonState State = ButtonState.Normal;

 

        #endregion

 

        #region 属性

 

        #region 颜色表

        [TypeConverter(typeof(ExpandableObjectConverter))]

        public class RenderColorTable

        {

            public Color TopStart { setget; }

            public Color TopEnd { setget; }

            public float Scale { setget; }

            public Color BottomStart { setget; }

            public Color BottomEnd { setget; }

            public Color BorderColor { setget; }

            public RenderColorTable(

                                    Color topStart, Color topEnd,

                                    Color bottomStart, Color bottomEnd,

                                    Color borderColor, float scale

                                   )

            {

                TopStart = topStart;

                TopEnd = topEnd;

                Scale = scale;

                BottomStart = bottomStart;

                BottomEnd = bottomEnd;

                BorderColor = borderColor;

            }

            public RenderColorTable() { }

 

        };

 

 

 

 

        private RenderColorTable normalColorTable

         = new RenderColorTable(

                        Color.FromArgb(227, 239, 255),

                        Color.FromArgb(193, 219, 255),

                        Color.FromArgb(179, 212, 255),

                        Color.FromArgb(192, 219, 255),

                        Color.FromArgb(119, 147, 185),

                        0.3f

                                );

        [Category("Appearance")]

        public RenderColorTable NomalColorTable

        {

            get

            {

                return normalColorTable;

            }

            set

            {

                normalColorTable = value;

                if (normalColorTable.Scale > 1f)

                    normalColorTable.Scale = 1f;

                if (normalColorTable.Scale < 0f)

                    normalColorTable.Scale = 0f;

                base.Invalidate();

            }

        }

 

 

        private RenderColorTable highlightColorTable

        = new RenderColorTable

                        (

                        Color.FromArgb(255, 244, 233),

                        Color.FromArgb(254, 226, 194),

                        Color.FromArgb(255, 207, 105),

                        Color.FromArgb(255, 249, 190),

                        Color.FromArgb(255, 219, 0),

                        0.3f

                        );

        [Category("Appearance")]

        public RenderColorTable HighlightColorTable

        {

            set

            {

                highlightColorTable = value;

                base.Invalidate();

            }

            get

            {

                return highlightColorTable;

            }

        }

 

        private RenderColorTable clickColorTable

                     = new RenderColorTable(

                        Color.FromArgb(255, 186, 108),

                        Color.FromArgb(253, 165, 101),

                        Color.FromArgb(251, 143, 66),

                        Color.FromArgb(255, 194, 109),

                        Color.FromArgb(148, 163, 194),

                        0.3f

                                );

        [Category("Appearance")]

        public RenderColorTable ClickColorTable

        {

            set

            {

                clickColorTable = value;

                base.Invalidate();

            }

            get

            {

                return clickColorTable;

            }

        }

        #endregion

 

        #region 外形

        private float cornerRadius = 2f;

        [Category("Appearance")]

        public float CornerRadius             //圆角矩形的角度

        {

            get

            {

                return cornerRadius;

            }

            set

            {

                cornerRadius = value;

                this.Invalidate();

            }

        }

        #endregion

 

        #endregion

 

        #region Mouse Event

        protected override void OnMouseUp(MouseEventArgs e)

        {

            base.OnMouseUp(e);

            if (e.Button != MouseButtons.Left) return;

            State = ClientRectangle.Contains(e.Location) ? ButtonState.Hover : ButtonState.Normal;

            this.Invalidate();

        }

 

        protected override void OnMouseDown(MouseEventArgs e)

        {

            base.OnMouseDown(e);

            if (e.Button != MouseButtons.Left) return;

            State = ButtonState.Pressed;

            this.Invalidate();

        }

        protected override void OnMouseEnter(EventArgs e)

        {

            base.OnMouseEnter(e);

            State = ButtonState.Hover;

            this.Invalidate();

        }

        protected override void OnMouseLeave(EventArgs e)

        {

            base.OnMouseLeave(e);

            State = ButtonState.Normal;

            this.Invalidate();

        }

 

        #endregion

 

        #region Render

        private Pen GetBorderPen()

        {

            if (!Enabled)

            {

                return new Pen(Color.FromArgb(119, 147, 185));

            }

            else

            {

                if (State == ButtonState.Pressed)

                {

                    return new Pen(clickColorTable.BorderColor);

                }

                else if (State == ButtonState.Hover)

                {

                    return new Pen(highlightColorTable.BorderColor);

                }

                else //(State == ButtonState.Normal)

                {

                    return new Pen(normalColorTable.BorderColor);

                }

            }

        }

        //获取渲染颜色表

        private ColorBlend GetColorBlend()

        {

            ColorBlend colorBlend = new ColorBlend();

            if (!Enabled)    //禁用状态下的颜色表

            {

                colorBlend.Colors = new Color[]

                {

                    Color.FromArgb(232,241,252),

                    Color.FromArgb(229,239,251),

                    Color.FromArgb(215,229,246),

                    Color.FromArgb(234,243,253)

                };

                colorBlend.Positions = new float[] { 0f, 0.3f, 0.35f, 1f };

            }

            else

            {

                if (State == ButtonState.Pressed)

                {

                    colorBlend.Colors = new Color[]

                    {

                        clickColorTable.TopStart,

                        clickColorTable.TopEnd,

                        clickColorTable.BottomStart,

                        clickColorTable.BottomEnd

                    };

                    colorBlend.Positions = new float[]

                    {

                        0f,

                        clickColorTable.Scale,

                        clickColorTable.Scale+0.05f,

                        1f

                    };

                }

                else if (State == ButtonState.Hover)

                {

                    colorBlend.Colors = new Color[]

                    {

                        highlightColorTable.TopStart,

                        highlightColorTable.TopEnd,

                        highlightColorTable.BottomStart,

                        highlightColorTable.BottomEnd

                    };

                    colorBlend.Positions = new float[]

                    {

                        0f,

                        highlightColorTable.Scale,

                        highlightColorTable.Scale,

                        1f

                    };

                }

                else  //正常状态

                {

 

                    colorBlend.Colors = new Color[]

                    {

                        normalColorTable.TopStart,

                        normalColorTable.TopEnd,

                        normalColorTable.BottomStart,

                        normalColorTable.BottomEnd

                    };

                    colorBlend.Positions = new float[]

                    {

                        0f,

                        normalColorTable.Scale,

                        normalColorTable.Scale,

                        1f

                    };

                }

 

            }

            return colorBlend;

 

        }

        /// <summary>

        /// 圆角矩形

        /// </summary>

        /// <param name="rect">矩形</param>

        /// <param name="radius">圆角半径</param>

        /// <returns></returns>

        private GraphicsPath RoundRectangle(RectangleF rect, float radius)

        {

            GraphicsPath gp = new GraphicsPath();

            float diameter = radius * 2f;

 

            gp.AddArc(rect.X + rect.Width - diameter, rect.Y, diameter, diameter, 270, 90);

            gp.AddArc(rect.X + rect.Width - diameter, rect.Y + rect.Height - diameter, diameter, diameter, 0, 90);

            gp.AddArc(rect.X, rect.Y + rect.Height - diameter, diameter, diameter, 90, 90);

            gp.AddArc(rect.X, rect.Y, diameter, diameter, 180, 90);

            gp.CloseFigure();

            return gp;

        }

        private void RenderBorder(Graphics g, Rectangle rect)

        {

            using (Pen pen = GetBorderPen())

            {

                Rectangle r = new Rectangle(rect.X, rect.Y, rect.Width - 1, rect.Height - 1);

                g.DrawPath(pen, RoundRectangle(r, cornerRadius));

            }

        }

        private void RenderCenter(Graphics g, Rectangle rect)

        {

            //线性渐变画刷

            LinearGradientBrush gb = new LinearGradientBrush(

                                       rect,

                                       Color.Black,

                                       Color.White,

                                       LinearGradientMode.Vertical);

 

            gb.InterpolationColors = GetColorBlend();//设置多色线性渐变表

            SolidBrush sb = new SolidBrush(this.BackColor);

            g.FillPath(gb, RoundRectangle(rect, cornerRadius));

 

            gb.Dispose();

        }

        #endregion

 

        #region 文本与图像的绘制

 

        protected virtual void DrawImage(Graphics g)

        {

            if (Image != null)

            {

                RectangleF imageRect = RogerBar.DrawingHelper.GetAlignPlacement(this.ImageAlign, this.ClientRectangle, Image.Size);

                g.DrawImage(Image, imageRect);

            }

 

 

        }

        protected virtual void DrawText(Graphics g)

        {

 

            g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;

            StringFormat format = new StringFormat();

            SizeF size = g.MeasureString(Text, Font, new SizeF(this.Width, this.Height), format);

            RectangleF textRect = DrawingHelper.GetAlignPlacement(TextAlign, this.ClientRectangle, size);

            SolidBrush sb = new SolidBrush(this.ForeColor);

            if (!Enabled) sb.Color = Color.FromArgb(141, 141, 141);

            g.DrawString(Text, Font, sb, textRect, format);

            sb.Dispose();

        }

        #endregion

        #region Override

 

    

        protected override void OnPaint(PaintEventArgs pevent)

        {

            Graphics g = pevent.Graphics;

            /* BufferedGraphicsContext currentContext = BufferedGraphicsManager.Current;

             BufferedGraphics buffer = currentContext.Allocate(pevent.Graphics, pevent.ClipRectangle);

             Graphics g = buffer.Graphics;*/

            //base.OnPaint(pevent);

            g.SmoothingMode = SmoothingMode.AntiAlias;

     

            RenderCenter(g, this.ClientRectangle);

            RenderBorder(g, this.ClientRectangle);

            DrawImage(g);

           

            DrawText(g);

 

            /*buffer.Render(pevent.Graphics);  //呈现图像至关联的Graphics  

            buffer.Dispose();

            g.Dispose();*/

        }

 

        #endregion

 

    }

}

 

 


2 0