Using LinearGradientBrush in C#

Well during my CSS change over I needed some background images for my headers. I wanted some simple gradient looks, but I only have 2 picture programs installed mspaint and Paint.Net, neither one of those does gradients (at least that I could find). I could download and install some picture program that has gradients but that is too much work and not much fun :)

So what do I do? I remember that there is some sort of Gradient stuff in GDI+ that I have never used. Then I do a simple google search and I turn up a nice walk through on how to use LinearGradientBrush on Bob Powell's GDI+ FAQ page. Then I open Visual Studio.Net and coded a little routine to generate a gradient image for my header. Here is the code for reference:

  1 using System.Drawing;
  2 using System.Drawing.Imaging;
  3 using System.Drawing.Drawing2D;
  5 ...
  7 public static void OutputGradientImage()
  8 {
  9 	using (Bitmap bitmap = new Bitmap(25, 75))
 10 	using (Graphics graphics = Graphics.FromImage(bitmap))
 11 	using (LinearGradientBrush brush = new LinearGradientBrush(
 12 		new Rectangle(0, 0, 25, 75),
 13 		Color.OliveDrab,
 14 		Color.LightGreen,
 15 		LinearGradientMode.Vertical))
 16 	{
 17 		brush.SetSigmaBellShape(0.25f, 0.75f);
 18 		graphics.FillRectangle(brush, new Rectangle(0, 0, 25, 75));
 19 		bitmap.Save("gradient.jpg", ImageFormat.Jpeg);
 20 	}
 21 }

It is amazing how easy this is to in .Net. Here is the image that the above code generated: 

I used that image as the background image for my top header. Then I changed the size to (25, 25) and generated the image for my sidebar / post headings.

At any rate I accomplished what I wanted to do, even it I had to code it myself. How big of a geek am I? ;)

Published Wednesday, October 27, 2004 11:24 PM by puzzlehacker


No Comments