Codelog

foreach(Snippet aSnippet in CodeLog){ aSnippet.GetSolution(); }

Glossy buttons in c#

without comments

Is there any way to create glossy, eye candy buttons in c# ?? Before starting off, we need to know what makes a thing glossy. There are two factors,

  • Color selection
  • Linear gradient fill over the control

Ok. Now lets see the implementation. For colors, we have Color class, but for Lineargradient ?? Yeah, we do have a LinearGradientBrush in c#.

Note: The task of making a button glossy will be acheived in the following order,

  • Drawing the border
  • Filling the lower rectangle with a solid color
  • Filling the upper rectangle with a linear gradient
  1. Include a button to the project (myGlossyButton)
  2. Change the FlatStyle of the myGlossyButton to Flat

    myGlossyButton.FlatStyle = FlatStyle.Flat;
  3. Handle the paint event of this button. Lets name the handler method as GlossyPainter
  4. In the GlossyPainter, first we need to give our button a border [task:1]. Say White border.

    e.Graphics.DrawRectangle(Pens.White, new Rectangle(0, 0, e.ClipRectangle.Width - 1, e.ClipRectangle.Height - 1));  //1 is subtracted from the size to make the border completely visible
  5. Next up, we need to fill the rectangle with some base color [task:2]. This time, we will fill the bottom half with some solid color and the upper half with some gradient color.

    SolidBrush aBaseSolidbrush = new SolidBrush(Color.FromArgb(150, Color.YellowGreen));  //FromArgb allows you to even specify the opacity of the colore.Graphics.FillRectangle(aBaseSolidBrush,  new Rectangle(2, (e.ClipRectangle.Height - 4) / 2, e.ClipRectangle.Width - 4, e.ClipRectangle.Height - 4));  //4 is subtracted just to leave a blank space between the border and the button     

  6. Filling the upper part of the button with the linear gradient color [task:3]

    LinearGradientBrush aLineargradientBrush = new LinearGradientBrush(new Rectangle(2, 2, e.ClipRectangle.Width - 4, (e.ClipRectangle.Height - 4) / 2), Color.FromArgb(255, Color.White), Color.FromArgb(100, aColor), 90);  //Specifying how big the linear gradient should be and in what direction the gradient should appear

    e.Graphics.FillRectangle(aLinearGradientBrush, new Rectangle(2, 2, e.ClipRectangle.Width - 4, (e.ClipRectangle.Height - 4) / 2));  //Filling the upperpart of the button
  7. Run the application, you should be seeing a glossy button

This is one of the ways to make a control look glossy. There are many ways to acheive this. If you know a really simple way share it with us.

Written by sudarsanyes

October 15th, 2008 at 9:34 am

Leave a Reply