Search code examples
c#xamlxamarinmobileicsharpcode

Xamarin Make Rectangle Inherit Position from Image


I was just trying to set this rectangle position I have via the code behind with c#. To begin I have the following Image inside the xaml page:

    <Image x:Name="danzo"
           Source="danzo.png"
           AbsoluteLayout.LayoutBounds="0.5, 0.2, 200, 200"
           AbsoluteLayout.LayoutFlags="PositionProportional">

    </Image>

As you can see it's just a regular image, not much special. In the constructor I attempt to just get this image and display it's dimensions (x, y, width, and height) like so:

Console.WriteLine("X Pos: {0}. Y Pos: {1}. Width: {2}. Height: {3}.", danzo.X, danzo.Y, danzo.Width, danzo.Height);

Yet it gives me back "X Pos: 0. Y Pos: 0. Width: -1. Height: -1.". Which isn't right at all. The image definitely has some REAL dimension values right? I have this console.writeline line of code AFTER the InitializeComponent function in the constructor if that matters.

However I created a button in the xaml and set it's clicked function to a function called "PrintImageDetails" with the EXACT same line of code as above. And the result? I get "X Pos: 105.714285714286. Y Pos: 121.142857142857. Width: 200. Height: 200."

So it seems like I can't really get the REAL image dimensions until after the constructor for whatever reason. (Or maybe there is some way and I'm missing it) This is important because I wanted to set the rectangle position to the image position. This is what leads me to the title of the question. Since I can't just get the real position immediately within the c# code behind, is it possible that I can make my rectangle inherit position from my image in .xaml? Below is my code for the rectangle. It's as simple as can be:

    <Rectangle x:Name="cropRect"
               AbsoluteLayout.LayoutBounds="0.5, 0.2, 200, 200"
               AbsoluteLayout.LayoutFlags="PositionProportional"
               BackgroundColor="Orange"
               Opacity="0.5">
        
    </Rectangle>

I want to also be able to maybe do some math operations while getting the position FROM the image, and putting it IN the rectangle. Such as division for example. If that's possible, an example on how to implement will be much appreciated.

Thank you to any who will help.


Solution

  • I didn't actually have to make the rect inherit from the image in xaml because this LayoutChildren function seems to have worked for me in the Code Behind. Link here How to get notified when ContentPage finishes loading

    So I'll be able to get the position of the image in that function and then be able to apply it to the rect. Works.