Xamarin.UITest: How To Retrieve Coordinates of Device Display

2.7k views Asked by At

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?

2

There are 2 answers

0
Brandon Minnick On BEST ANSWER

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;
0
Cocowalla On

Brandon's answer works well, but app.Query() without a predicate is painfully slow, since it returns an array and not an IEnumerable<AppResult> - in the app I'm currently working with it takes ~10 seconds.

As a faster alternative, you can specify the automation ID (or some other predicate) of an element you know to be near the root. For example, assuming your views are using ContentPage, you can use:

var content = app.Query("content").First();
var rect = content.Rect;

This completes in less than 1s.

Do note that this won't give you the precise display size - it's the size of the ContentPage, so it will be slightly smaller than the display size (but for my use case, that's fine).