How to create Gradient effect background using C#

Ever wanted to create a gradient image dynamically? This can easily be done using C# with the following snipplet of code. We can also specify the width, height, gradient direction (horizontal or vertical), and the two colors.

int intWidth = Convert.ToInt16(txbWidth.Text);
int intHeight = Convert.ToInt16(txbHeight.Text);
banner.GradientDirection = Convert.ToInt16(rcbDirection.SelectedValue);
LinearGradientMode gradientMode;
if (banner.GradientDirection == 1)
       gradientMode = LinearGradientMode.Vertical;
else
       gradientMode = LinearGradientMode.Horizontal;

using (Bitmap bitmap = new Bitmap(intWidth, intHeight))
    using (Graphics graphics = Graphics.FromImage(bitmap))
        using (LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, intWidth, intHeight),
               FirstColor, SecondColor, gradientMode))
                {
                   //brush.SetSigmaBellShape(intWidth / 100, intHeight / 100);
                    graphics.FillRectangle(brush, new Rectangle(0, 0, intWidth, intHeight));
                    MemoryStream stream = new MemoryStream();
                    bitmap.Save(stream, ImageFormat.Jpeg);
                    Byte[] bytes = stream.ToArray();
                 }

More info at: http://weblogs.asp.net/whaggard/archive/2004/10/27/248878.aspx

Categories: C#
Tags: