C # Create Gradient Image

How to create a gradient image (with a given height and width, start the color and the end of the color) using C #? Does anyone have a simple sample fragment? Thanks!

+5
source share
3 answers

You can do this using LinearGradientBrush . for example

// using System.Drawing;
// using System.Drawing.Imaging;
// using System.Drawing.Drawing2D;

public static void OutputGradientImage()
{
    using (Bitmap bitmap = new Bitmap(100, 100)) // 100x100 pixels
    using (Graphics graphics = Graphics.FromImage(bitmap))
    using (LinearGradientBrush brush = new LinearGradientBrush(
        new Rectangle(0, 0, 100, 100),
        Color.Blue,
        Color.Red,
        LinearGradientMode.Vertical))
    {
        brush.SetSigmaBellShape(0.5f);
        graphics.FillRectangle(brush, new Rectangle(0, 0, 100, 100));
        bitmap.Save("gradientImage.jpg", ImageFormat.Jpeg);
    }
}
+10
source

LinearGradientBrush is your friend here:


    Bitmap bmp = new Bitmap(Width, Height);
    Graphics g = Graphics.FromImage(bmp);
    LinearGradientBrush lgb = new LinearGradientBrush(new Point(0, 0), new Point(Width, Height), Color.Black, Color.Red);
    g.FillRectangle(lgb, 0, 0, Width, Height);
    bmp.Save("FileName");
    lgb.Dispose();
    g.Dispose();
    bmp.Dispose();

+2
source
protected override void OnPaintBackground(PaintEventArgs e)
{
    using (Brush b = new LinearGradientBrush(ClientRectangle, Color.Red, Color.Blue, LinearGradientMode.ForwardDiagonal))
        e.Graphics.FillRectangle(b, ClientRectangle);
}

It is as easy as you can do it.

0
source

All Articles