Let the user move the center point of an elliptical gradient in C#

elliptical gradient

The example Fill an area with an elliptical gradient in C# shows how to make a brush that fills an area with an elliptical gradient. This example just lets the user move the gradient’s center point.

When you move the mouse, the following code saves the mouse’s current position in the variable CenterPoint and then refreshes the form.

// Select the ellipse's center point.
private PointF CenterPoint;
private void Form1_MouseMove(object sender, MouseEventArgs e)
    CenterPoint = e.Location;

The following Paint event handler fills the form with an elliptical gradient with the selected center. (The line that sets the gradient’s center is shown in blue.)

// Draw the elliptical gradient background.
private void Form1_Paint(object sender, PaintEventArgs e)
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

    // Make a GraphicsPath to represent the ellipse.
    Rectangle rect = new Rectangle(
        10, 10,
        this.ClientSize.Width - 20,
        this.ClientSize.Height - 20);
    GraphicsPath path = new GraphicsPath();

    // Make a PathGradientBrush from the path.
    using (PathGradientBrush br = new PathGradientBrush(path))
        br.CenterPoint = CenterPoint;
        br.CenterColor = Color.Blue;
        br.SurroundColors = new Color[] { this.BackColor };
        e.Graphics.FillEllipse(br, rect);

The code creates a rectangle to define the gradient’s ellipse. It creates a GraphicsPath object and uses its AddEllipse method to add an ellipse to it.

Next the code creates a PathGradientBrush from the GraphicsPath. It sets the brush’s center point to the selected point, sets the center color to blue, and sets the surround colors to the form’s background color. Finally the code fills the rectangle with the brush.

Download Example   Follow me on Twitter   RSS feed

This entry was posted in graphics and tagged , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.