在 Android 中测量“fitCenter”imageView 的边距

Axe*_*man 2 android margins imageview android-layout

给定一个简单的RelativeLayout,如下所示:

    <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>
Run Code Online (Sandbox Code Playgroud)

布局边框和图像边框之间的左/上间距取决于在 imageView 中加载的图像的宽/高比。

在此处输入图片说明

在此布局中显示图像后,我如何(以编程方式)知道实际边距(青色区域的宽度和高度)?

Mah*_*oud 7

此方法将计算在 FIT_CENTER和所有其他相关值之后包围对象新矩形

它应该适用于对象和容器的所有情况。

在此处输入图片说明

 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);
    }
Run Code Online (Sandbox Code Playgroud)

您可以使用FrameLayout将视图放置在您想要的任何位置,在使用前一种方法以及缩放对象的新 x、y、宽度、高度之后。