Roee Palmon
Roee Palmon

Reputation: 13

Four Color Gradient Rectangle in Windows Form C# Using?

I want to be able to make a four color gradient with 1 color from each corner. I want to be able to do this in a Rectangle drawing using the Graphics in Windows Form C#. Can anyone help with the code for making one if possible? Thanks.

Upvotes: 1

Views: 1031

Answers (1)

steve16351
steve16351

Reputation: 5812

You can use a PathGradientBrush to do this. To get a nice smooth mix, I have set the centre colour to an average of all of the colours involved.

private void Form1_Paint(object sender, PaintEventArgs e)
{
    var colorArray = new Color[] { Color.Red, Color.Blue, Color.Green, Color.Yellow };        
    GraphicsPath graphicsPath = new GraphicsPath();
    graphicsPath.AddRectangle(ClientRectangle);

    using (Graphics graphics = this.CreateGraphics())
    using (PathGradientBrush pathGradientBrush = new PathGradientBrush(graphicsPath)
    {
        CenterColor = Color.FromArgb((int)colorArray.Average(a => a.R), (int)colorArray.Average(a => a.G), (int)colorArray.Average(a => a.B)),
        SurroundColors = colorArray
    })
    {
        graphics.FillPath(pathGradientBrush, graphicsPath);
    }
}

Result:

enter image description here

Upvotes: 3

Related Questions