I want to use a LinearGradientBrush to fill a rectangular range on a canvas with a gradient. The catch is, I want the gradient to appear the same on both sides of the rectangle, no matter how large the rectangle is.
What I'm trying to draw is something like this:
Here's my first attempt:
LinearGradientBrush brush = new LinearGradientBrush();
brush.SpreadMethod = GradientSpreadMethod.Reflect;
brush.GradientStops.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#FF0000FF"), 0.0));
brush.GradientStops.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#22FFFFFF"), 0.25));
brush.GradientStops.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#22FFFFFF"), 0.75));
brush.GradientStops.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#FF0000FF"), 1.00));
brush.StartPoint = new Point(0, 0);
brush.EndPoint = new Point(1, 0);
Rectangle rect = new Rectangle();
rect.Width = 100;
rect.Height = 100;
rect.Fill = brush;
Canvas.SetLeft(rect, 50);
Canvas.SetTop(rect, 50);
MyCanvas.Children.Add(rect);
Rectangle rect2 = new Rectangle();
rect2.Width = 300;
rect2.Height = 100;
rect2.Fill = brush;
Canvas.SetLeft(rect2, 50);
Canvas.SetTop(rect2, 200);
MyCanvas.Children.Add(rect2);
Not quite right; the bigger the rectangle, the wider the gradients appear:
I tried setting MappingMode to Absolute, but that doesn't work either.
LinearGradientBrush brush = new LinearGradientBrush();
brush.MappingMode = BrushMappingMode.Absolute;
brush.SpreadMethod = GradientSpreadMethod.Reflect;
brush.GradientStops.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#FF0000FF"), 0.0));
brush.GradientStops.Add(new GradientStop((Color)ColorConverter.ConvertFromString("#22FFFFFF"), 0.25));
brush.StartPoint = new Point(0, 0);
brush.EndPoint = new Point(50, 0); //I want the gradient to be across 50 pixels
Rectangle rect = new Rectangle();
//Everything else is the same
This give me something that looks like this:
which is way off. Any suggestions?
One way to accomplish this is to create a custom control
.
Compose it with 3 rectangles on a Grid
;