测量&QUOT的保证金; fitCenter" ImageView的Android中 [英] Measuring margin of a "fitCenter" imageView in Android
问题描述
给出一个简单的RelativeLayout是这样的:
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>
的
布局边界和图象边界之间的左/顶间距取决于在ImageView的所述图像被负载的W / H比值
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?
推荐答案
这个方法计算出的新的矩形这之后FIT_CENTER 和所有的等相关数值界定的对象。
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
// 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 的,无论你使用previous方法与新的X,Y,宽度,缩放对象的高度后,要视图位置。
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.
这篇关于测量&QUOT的保证金; fitCenter&QUOT; ImageView的Android中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!