1
votes

In my MainPage.xaml, which is a ContentPage, I have a GradientColorStack.

<local:GradientColorStack x:Name="ColorStack" StartColor="#FF0000" EndColor="#FFFF00">

This class has StackLayout as a base class and it presents a background that has a gradient color fill. I got this idea from here.

public class GradientColorStack : StackLayout

The problem is that on device orientation change, the background color fill is not re-drawn. Thus in landscape orientation there is a big gap filled with black where you can see through the GradientColorStack to the ContentPage background.

Is there a way to force the GradientColorStack to re-draw on device orientation change?

2

2 Answers

1
votes

iOS Version

I added the following method to my renderer class:

protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    SetNeedsDisplay();
    base.OnElementPropertyChanged(sender, e);
}

This causes the Draw() method of the same class to be called on a screen orientation event. In Draw() I now find the existing CAGradientLayer (if it exists) and remove it from the super layer and then just let the Draw() routine then calculate a new CAGradientLayer as usual, which it then adds to the NativeView.Layer.Sublayers collection as usual.

Thanks to @SHUBHAM SHARMA for the tip of using SetNeedsDisplay() but this post was also required to get the solution working.


Android Version

It turns out the Android version was already working to correctly redraw the gradient layer (see tutorial). I think this is because of the following method in my renderer class:

protected override void OnElementChanged(ElementChangedEventArgs<StackLayout> e)
{
    base.OnElementChanged(e);

    if (e.OldElement != null || Element == null)
    {
        return;
    }

    var stack = e.NewElement as GradientColorStack;
    this.StartColor = stack.StartColor;
    this.EndColor = stack.EndColor;
}
0
votes

You can use ForceLayout() in android Renderer and SetNeedDisplay() in iOS Renderer because these function are forcefully refresh the layout.