Question

I want project/transform the bounds of a view into screen coordinates. The local bounds are 0,0,1280,628 and the ActionBar just above my view is 108 pixel high.

The problem is that view.getLocationOnScreen transforms the first point as 0x108 which is correct. But it also transforms all other corners (1280x0, 1280x628, 0x628) again into 0x180. Any idea why?

That's my code.

public static void getLocationOnScreen(View view, final Rect src, Rect dst) {
    if (view == null || src == null)
        return;

    if (dst == null)
        dst = new Rect();

    Point[] corners = RectTools.getCornerPoints(src);
    int[] location = new int[2];

    for (int i = 0; i < corners.length; i++) {
        Point current = corners[i];
        location[0] = current.x;
        location[1] = current.y;

        view.getLocationOnScreen(location);

        corners[i] = new Point(location[0], location[1]);
    }

    createRectangle(dst, corners);
}
Was it helpful?

Solution

Ok, I just understood the function wrong - maybe because I'm coming from the Microsoft .NET C# world where you can easily transform coordinates from control to screen and vice versa. Anyway, the view.getLocationOnScreen is just returning the transformed upper-left corner of the view. So you have to use it as an offset.

public static void getLocationOnScreen(View view, final Rect src, Rect dst) {
    if (view == null || src == null)
        return;

    if (dst == null)
        dst = new Rect();

    int[] location = new int[2];
    view.getLocationOnScreen(location);
    int offsetX = location[0];
    int offsetY = location[1];

    dst.set(src.left + offsetX, src.top + offsetY, src.right + offsetX,
            src.bottom + offsetY);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top