How can I create a gradient image (with a given height & width, start color and end color) using C#? Does anybody have a simple sample snippet? Thank you!
You can do this using a 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);
}
}
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();
protected override void OnPaintBackground(PaintEventArgs e)
{
using (Brush b = new LinearGradientBrush(ClientRectangle, Color.Red, Color.Blue, LinearGradientMode.ForwardDiagonal))
e.Graphics.FillRectangle(b, ClientRectangle);
}
That's about as simple as you can make it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.