-2

In WPF, is there a way to draw a line (in any orientation) that blends from one colour to another?

For example, I want to draw a line from point A to point B, where A is Red and B is Black. The line could be vertical, horizontal, or any orientation.

I have tried using a LinearGradientBrush, but this requires you to set an angle or Start/End positions. This won't work for me as I need to be able to draw the line at any two points in any orientation and still get it to blend. I could in theory compute the angle (or Start/End positions) for the LinearGradientBrush for each line and update it when ever the points of the line changes, but this wouldn't be ideal and would be an expensive operation for the number of lines I plan on drawing.

RadialGradientBrush also doesn't seem to help.

wforl
  • 91
  • 9
  • `RadialGradientBrush` should work if you set the [Center and the GradientOrigin](https://learn.microsoft.com/en-us/windows/communitytoolkit/brushes/radialgradientbrush#properties) equal to one of the endpoints of the line. – Olivier Jacot-Descombes Mar 09 '22 at 10:30
  • Or you can calculate the angle with `Math.Atan2` of the vector B - A. – Olivier Jacot-Descombes Mar 09 '22 at 10:36
  • @OlivierJacot-Descombes yes, I did mention about computing it on the fly, but was wondering if there was something that didn't require having to do that. I will be drawing lots of lines that will be moving as the user drags them around, so not really ideal. – wforl Mar 09 '22 at 10:38

1 Answers1

1

This following LinearGradientBrush "blends" from red to black regardless of the Width of the Grid element:

<Grid Height="10" Width="100">
    <Grid.Background>
        <LinearGradientBrush>
            <GradientStop Color="Red" />
            <GradientStop Color="Black" Offset="1" />
        </LinearGradientBrush>
    </Grid.Background>
</Grid>
mm8
  • 163,881
  • 10
  • 57
  • 88