65.9K
CodeProject is changing. Read more.
Home

Gradient Color C#, ASP.NET

Apr 14, 2013

CPOL
viewsIcon

11587

downloadIcon

213

This a trick to generate random gradient color in your ASP.NET project, which will change randomly on every post-back.

Introduction

This is a trick to generate a random gradient color in your ASP.NET project, which will change randomly on every post-back.

Background

Required references are given below:

using System.Drawing.Drawing2D;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;

Using the code  

Following is my code for the ProcessRequest method handler: 

public void ProcessRequest (HttpContext context) {

    string[] fColor = new string[] {"Gray","Skyblue","Green","Yellow" };
    string[] sColor = new string[] {"white","Red","Pink","blue" };
    Random r = new Random();
    string firstColor = fColor[r.Next(fColor.Length -1)];
    string secondColor = sColor[r.Next(sColor.Length - 1)];
    Int32 height = 786;
    Bitmap img = new Bitmap(2, height);
    Graphics g = Graphics.FromImage(img);
    //Drawing2D
    LinearGradientBrush brush = new LinearGradientBrush(
        Point.Empty, 
        new Point(0, height), 
        this.getColorFromString(firstColor), 
        this.getColorFromString(secondColor));
    
    g.DrawRectangle(new System.Drawing.Pen(brush, 10), new Rectangle(0, 0, 2, height));
    context.Response.ContentType = ".jpg";
    MemoryStream str = new MemoryStream();
    img.Save(str, ImageFormat.Jpeg);
    context.Response.BinaryWrite(str.ToArray());
}
private System.Drawing.Color getColorFromString(string SColor)
{
    return System.Drawing.Color.FromName(SColor);
}

Points of Interest

Provide every postback a new background whenever user browses pages of the website.