65.9K
CodeProject is changing. Read more.
Home

Getting the Office 2010 button like Gradient

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Jun 17, 2011

CPOL
viewsIcon

24003

Here is how you can achieve Gradients used in Office 2010 Buttons with a glow at the bottom.

I came across a requirement to achieve a Office 2010 like gradient, if you take a closer look at the Office 2010 buttons you can see the gradient is not actually linear, it is more like a light source as in photo editors. I have raised this in an MSDN article and received a clue on achieving the solution. Here is the generic solution - a reusable office button.
public class OfficeButton : Button
  {
    public OfficeButton() : base() { }
    public Color GradientGlowColor { get; set; }
    protected override void OnPaint(PaintEventArgs pevent)
    {
      Bitmap bmp = new Bitmap(this.Width,this.Height);
      Rectangle rect = this.ClientRectangle;
      
      Graphics g = Graphics.FromImage(bmp);
      g.Clear(GradientGlowColor);
      g.InterpolationMode = InterpolationMode.NearestNeighbor;
      using (SolidBrush brush = new SolidBrush(this.BackColor))
      {
        g.FillRectangle(brush, rect);
      }
      rect.Inflate(-1, -1);
      rect.Width -= 1; rect.Height -= 1;
      using (Pen pen = new Pen(GradientGlowColor))
      {
        g.DrawRectangle(pen, rect);
      }
      RectangleF[] CornerDots = new RectangleF[]
        {
          new RectangleF(rect.Left + 1, rect.Top + 1, 1, 1),
          new RectangleF(rect.Right - 1, rect.Top + 1, 1, 1),
          new RectangleF(rect.Left + 1, rect.Bottom - 1, 1, 1),
          new RectangleF(rect.Right - 1, rect.Bottom - 1, 1, 1)
        };
      using (SolidBrush brush = new SolidBrush(this.GradientGlowColor))
      {
        g.FillRectangles(brush, CornerDots);
      }
      using (GraphicsPath ellipse = new GraphicsPath())
      {
        float offset = this.Width / 5;
        
        ellipse.AddEllipse(new RectangleF( - offset / 2, 0, this.Width + offset, 30));
        ellipse.Transform(new Matrix(1, 0, 0, 1, 0, (this.Height - 15)));
        using (PathGradientBrush p = new PathGradientBrush(ellipse))
        {
          p.CenterColor = this.GradientGlowColor;
          p.SurroundColors = new Color[] { Color.FromArgb(12,this.GradientGlowColor) };
          p.FocusScales = new PointF(0.6F, 0.1F);
          g.FillPath(p, ellipse);
        }
      }
      using (Pen pen = new Pen(this.BackColor))
      {
        rect = this.ClientRectangle;
        rect.Height -= 1; rect.Width -= 1;
        g.DrawRectangle(pen, rect);
      }
      pevent.Graphics.DrawImage(bmp, Point.Empty);
    }
  }
Original thread is here[^] Posting here, therefore it may help someone who is in need.