Q:

Measuring margin of a "fitCenter" imageView in Android

Given a simple RelativeLayout like this: 
    <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#0fffff">
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter"
        android:src="@drawable/img001" />
    </RelativeLayout>

the left/top spacing between the layout border and the image border depends on the W/H ratio of the image being load in the imageView.

How can I know (programmatically) the real margin (width and height of the cyan area) after an image is shown in this layout?

A:

This method will calculate the new rectangle which bounds the object after FIT_CENTER and all other related values.
It should work on all cases of object and container.

 public static Rect calculateFitCenterObjectRect(float containerWidth, float containerHeight, float objectWidth, float objectHeight) {

        // scale value to make fit center
        double scale = Math.min( (double)containerWidth / (double)objectWidth, (double)containerHeight / (double)objectHeight);

        int h = (int) (scale * objectHeight); // new height of the object
        int w = (int) (scale * objectWidth); // new width of the object

        int x = (int) ((containerWidth - w) * 0.5f); // new x location of the object relative to the container
        int y = (int) ((containerHeight - h) * 0.5f); // new y  location of the object relative to the container

        return new Rect(x, y, x + w, y + h);
    }

You can use FrameLayout to position the view wherever you want after using the previous method with the new x, y, width, height of the scaled object. 

