给定一个像这样的简单的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 中加载的图像的宽/高比。
在该布局中显示图像后,如何(以编程方式)知道实际边距(青色区域的宽度和高度)?
该方法将计算在 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);
}
您可以使用框架布局使用先前的方法和缩放对象的新 x、y、宽度、高度后,将视图定位到任意位置。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)