Graphics.GetNearestColor(Color) Method

Definition

Gets the nearest color to the specified Color structure.

C#
public System.Drawing.Color GetNearestColor(System.Drawing.Color color);

Parameters

color
Color

Color structure for which to find a match.

Returns

A Color structure that represents the nearest color to the one specified with the color parameter.

Examples

The following code example is designed for use with Windows Forms, and it requires PaintEventArgs e, which is a parameter of the Paint event handler. The code performs the following actions:

  • Creates an arbitrary color with ARGB coordinates (255, 165, 63, 136).

  • Creates a solid brush and sets its color to the specified color.

  • Fills an ellipse using the arbitrary color.

  • Creates a second color and sets its value to the nearest system ARGB color.

  • Fills a second ellipse with this color.

The result is two ellipses: the first drawn with the arbitrary specified color and the second drawn with the system color nearest the specified color.

C#
private void GetNearestColorColor(PaintEventArgs e)
{
    // Create solid brush with arbitrary color.
    Color arbColor = Color.FromArgb(255, 165, 63, 136);
    SolidBrush arbBrush = new SolidBrush(arbColor);

    // Fill ellipse on screen.
    e.Graphics.FillEllipse(arbBrush, 0, 0, 200, 100);

    // Get nearest color.
    Color realColor = e.Graphics.GetNearestColor(arbColor);
    SolidBrush realBrush = new SolidBrush(realColor);

    // Fill ellipse on screen.
    e.Graphics.FillEllipse(realBrush, 0, 100, 200, 100);
}

Applies to

Product Versions
.NET 8 (package-provided), 9 (package-provided)
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7 (package-provided), 4.7, 4.7.1 (package-provided), 4.7.1, 4.7.2 (package-provided), 4.7.2, 4.8 (package-provided), 4.8, 4.8.1
.NET Standard 2.0 (package-provided)
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9