Axeman
Axeman

Reputation: 174

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.

enter image description here

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

Upvotes: 2

Views: 1219

Answers (2)

Mahmoud
Mahmoud

Reputation: 2893

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.

enter image description here

 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.

Upvotes: 7

Marcus
Marcus

Reputation: 6717

If you know the width of the ImageView, like this

int ivWidth = iv.getMeasuredWidth(); 

and the total width of the layout (your RelativeLayout), like this

int layoutWidth = yourLayout.getWidth();

then, you can easily get the horizontal margin, like this

int horizontalMargin = (layoutWidth - ivWidth)/2; 

And the same goes for height.

You should call functions like getWidth and getHeight after the dimensions of your layout have been calculated, as described by Veer's and Khan's answer on How to get the width and height of an Image View in android?. Calling getWidth or getHeight in onCreate will return 0.

Upvotes: 1

Related Questions