Find the color of a point in a LinearGradientBrushJanuary 28, 2008 at 7:54 am | Posted in .Net, C#, Silverlight, WPF | 6 Comments
I became intrigued by the problem of finding the color at any point of a rectangle that has been filled with a LinearGradientBrush. There is are techniques for doing this by essentially sampling the pixel at a rendered point but I wanted to approach the problem algorithmically.
I developed the following method which receives a rectangle object that has been filled with a LinearGradientBrush and a point relative to the upper left corner of the rectangle and returns the calculated color at that point. There are no restrictions on the Start/Stop Points or the number of GradientStops. The ColorInterpolationMode can be either SRgbLinearInterpolation (default) or ScRgbLinearInterpolation. The GradientSpreadMethod is required to be the default (Pad).
There are two methods below:
Color GetColorAtPoint(Rectangle r, Point p) – finds the color at any point of a LinearGradientBrush filled rectangle.
private Double dist(Point px, Point po, Point pf) – helper method for GetColorAtPoint.
To use, copy both methods to your class and call GetColorAtPoint() with a rectangle and point.
The method works by projecting the input point onto the vector that is described by the LinearGradientBrush Start/Stop points. There are special cases for horizontal and vertical lines. The width of the line is calculated as well as the relative distance of the projected point from the StartPoint (using the dist() method). The GradientStops are ordered and two stops are found that are the closest the projected point. The color channel values are interpolated based on the relative position of the projected point and these two stops. The values are assembled into a color and returned.
You can download a demo of this method here.