Search code examples
c#xamarinui-testingxamarin.uitest

Xamarin.UITest: How To Retrieve Coordinates of Device Display


I am writing a UITest in C# using Xamarin.UITest.

How can I retrieve the coordinates of the device's screen dynamically in the UITest?


Solution

  • In Xamarin.UITest, when you call app.Query(), the first query result will return the device display. You can then grab the XY coordinates using the Rect property.

    Below is a sample REPL output showing the result of app.Query().First(), and sample code assigning the XY coordinates to variables in your UITest.

    Sample Output from REPL

    Output From REPL

    Sample Code

    var windowQuery = app.Query().First();
    
    var topLeftXCoordinate = windowQuery.Rect.X;
    var topLeftYCoordinate = windowQuery.Rect.Y;
    
    var topRightXCoordinate = windowQuery.Rect.X + windowQuery.Rect.Width;
    var topRightYCoordinate = windowQuery.Rect.Y;
    
    var bottomLeftXCoordinate = windowQuery.Rect.X;
    var bottomLeftYCoordinate = windowQuery.Rect.Y + windowQuery.Rect.Height;
    
    var bottomRightXCoordinate = windowQuery.Rect.X + windowQuery.Rect.Width;
    var bottomRightYCoordinate = windowQuery.Rect.Y + windowQuery.Rect.Height;
    
    var centerXCoordinate = windowQuery.Rect.CenterX;
    var centerYCoordinate = windowQuery.Rect.CenterY;