C#创建渐变图像

时间:2009-09-29 17:31:29

标签: c# .net

如何使用C#创建渐变图像(具有给定的高度和宽度,开始颜色和结束颜色)?有没有人有一个简单的样本片段?谢谢!

3 个答案:

答案 0 :(得分:10)

您可以使用LinearGradientBrush执行此操作。例如

// 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);
    }
}

答案 1 :(得分:2)

LinearGradientBrush是你的朋友:


    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 :(得分:0)

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

这就像你能做到的一样简单。