Search code examples
c#mathgeometrymaui

Coloring a border diagonally in MAUI/C# - Perpendicular line on the diagonal in a rectangle


I' working on an app, where I want to color a Border element diagonally, as indicated in the following sketch:

enter image description here

My approach is to use a LinearGradient similar to

BackgroundBrush = new LinearGradientBrush(new GradientStopCollection(){
                    new GradientStop(Colors.Blue, 0.5f),
                    new GradientStop(Colors.Red, 0.5f),
                }, new Point(0, 1), new Point(1, 0));

This solution however, only works on square shapes. As soon as the shape becomes rectangular, the diagonal "line" does no longer go through the respective corners. I'm quite sure that I need to adjust the start and end point as outlined in the following sketch:

enter image description here

I know the locations of point A, B, C and D. I need the gradient to start and end, where the perpendicular of the diagonal line intersects the border. However, I'm not sure how I can calculate these points.


Solution

  • If perpendicular goes through the middle of BD diagonal, coordinate origin is in point A, rectangle width is a, height is b, and a>=b, then F point coordinate is

    F.x = (a*a+b*b)/(2*a)
    

    (for example, we can use scalar product of BD and EF to get this formula)

    and

    E.x = a-Fx
    

    When a<=b, E point will lie at AD side with alike formula for y-coordinate and 2b in denominator.