【问题标题】:Measuring margin of a "fitCenter" imageView in Android在 Android 中测量“fitCenter”imageView 的边距
【发布时间】:2015-02-14 15:35:48
【问题描述】:

给定一个像这样的简单 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 中加载的图像的宽高比。

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

【问题讨论】:

    标签: android android-layout imageview margins


    【解决方案1】:

    此方法将计算 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);
        }
    

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

    【讨论】:

      【解决方案2】:

      如果你知道ImageView的宽度,像这样

      int ivWidth = iv.getMeasuredWidth(); 
      

      以及布局的总宽度(你的RelativeLayout),像这样

      int layoutWidth = yourLayout.getWidth();
      

      然后,你可以很容易地得到水平边距,像这样

      int horizontalMargin = (layoutWidth - ivWidth)/2; 
      

      身高也是如此。

      如 Veer 和 Khan 在 How to get the width and height of an Image View in android? 上的回答所述,在计算完布局的尺寸后,您应该调用 getWidthgetHeight 之类的函数。 在onCreate 中调用getWidthgetHeight 将返回0。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-23
        • 1970-01-01
        相关资源
        最近更新 更多