给出一个像这样的简单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>
布局边框与图像边框之间的左/上间距取决于imageView中正在加载的图像的W / H比。
在此布局中显示图像后,如何(以编程方式)知道真实边距(青色区域的宽度和高度)?
答案 0 :(得分:4)
此方法将计算在
它应该适用于对象和容器的所有情况。
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
// calculate the empty space between the object and the container after fit center
int marginRight = (int) ((containerWidth - w) * 0.5f);
int marginLeft = (int) ((containerWidth - w) * 0.5f);
int marginTop = (int) ((containerHeight - h) * 0.5f);
int marginBottom = (int) ((containerHeight - h) * 0.5f);
return new Rect(x, y, x + w, y + h);
}
您可以使用 FrameLayout 将视图定位到使用前一个方法后所需的位置,并使用缩放对象的新x,y,宽度和高度。
答案 1 :(得分:1)
如果你知道ImageView
的宽度,就像这样
int ivWidth = iv.getMeasuredWidth();
和布局的总宽度(您的RelativeLayout
),如下所示
int layoutWidth = yourLayout.getWidth();
然后,您可以轻松获得水平边距,如此
int horizontalMargin = (layoutWidth - ivWidth)/2;
同样适合身高。
在计算布局尺寸后,您应该调用getWidth
和getHeight
等函数,如Veer&and和Khan在How to get the width and height of an Image View in android?上的回答所述。
在getWidth
中呼叫getHeight
或onCreate
将返回0.