Weird anchor behavior when setting HeightRequest and scaling (possible bug - iOS only)

FunderFunder Member ✭✭

If the anchor of an element is set to 0 and then the HeightRequest (or WidthRequest) is changed before or after scaling, the position is off.

Example

Take a look at the below screen shot. The boxes are identical except that red box needs the height to be set to 160.

This is the xaml:

    <AbsoluteLayout
        Margin="20">
        <Frame
            HeightRequest="160"
            WidthRequest="160"
            BorderColor="Black"
            CornerRadius="0"
            TranslationX="99"
            Padding="1" />

        <BoxView
            x:Name="rightBox"
            AnchorX="0"
            AnchorY="0"
            HeightRequest="160"
            WidthRequest="160"
            TranslationX="100"
            TranslationY="1"
            Color="Green" />



        <Frame
            HeightRequest="160"
            WidthRequest="160"
            BorderColor="Black"
            CornerRadius="0"
            TranslationY="200"
            TranslationX="100"
            Padding="1" />

        <BoxView
            x:Name="wrongBox"
            AnchorX="0"
            AnchorY="0"
            HeightRequest="150"
            WidthRequest="160"
            Color="Red"
            TranslationY="201"
            TranslationX="101" />

        <Button Text="Invoke"
                Clicked="HandleButton"
                TranslationY="400" />

    </AbsoluteLayout>

When tapping the "invoke" button we want to scale both elements to 0.5.
It will trigger this code:

void HandleButton (Object sender, EventArgs e)
{
    rightBox.Scale = 0.5;
    wrongBox.HeightRequest = 160;
    wrongBox.Scale = 0.5;
}

This is the result:

I would expect the red button to be inside the frame like the green box.

It looks like the anchoring is ignored. Even if I set the anchor to zero (again) and set the translation again I get the same result.

This only happens on iOS. On Android I get the expected result.

How do prevent this from happening and get the red box correctly positioned inside the frame?

Answers

  • ColeXColeX Member, Xamarin Team Xamurai
    edited July 12

    Firstly , check the definition of AnchorX.

    Gets or sets the X component of the center point for any transform, relative to the bounds of the element.

    Any transform includes size transform .

    So when you set HeightRequest to change the height , it also obeys the rules ,check the image below with setting HeightRequest only.

    Solution

    Set Anchor after changing the height.

           <BoxView
            x:Name="wrongBox"   
            HeightRequest="150"
            WidthRequest="160"
            Color="Red"
            TranslationY="201"
            TranslationX="101" />
    
    
            wrongBox.HeightRequest = 160;
            wrongBox.AnchorX = 0;
            wrongBox.AnchorY = 0;
            wrongBox.Scale = 0.5;
    

Sign In or Register to comment.