ImageView高度相对于宽度

Zde*_*pič 2 android imageview android-layout android-imageview

我有这个布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/AppTheme.Widgets.Box"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:scaleType="centerCrop"
        android:background="#eee"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="7dp"
        android:gravity="center"/>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

所以,我正在从Web上将远程图像加载到ImageView中.我知道图像的尺寸,所以我知道宽度:高度比.现在,当我初始化我的布局时,我需要以某种方式应用这个比例,所以它在应用程序中不会像疯了一样跳跃.

mak*_*tar 7

对于这种情况,我创建了一个自定义ImageView,它保持相对于宽度的高度.它具有自定义属性'height_ratio',乘以宽度以获得高度:

DynamicHeightImageView.java:

/**
 * An {@link android.widget.ImageView} layout that maintains a consistent width to height aspect ratio.
 */
public class DynamicHeightImageView extends ImageView {

    private float mHeightRatio;

    public DynamicHeightImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.DynamicHeightImageView, 0, 0);
        try {
            mHeightRatio = ta.getFloat(R.styleable.DynamicHeightImageView_height_ratio, 0.0f);
        } finally {
            ta.recycle();
        }
    }

    public DynamicHeightImageView(Context context) {
        super(context);
    }

    public void setHeightRatio(float ratio) {
        if (ratio != mHeightRatio) {
            mHeightRatio = ratio;
            requestLayout();
        }
    }

    public double getHeightRatio() {
        return mHeightRatio;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mHeightRatio > 0.0f) {
            // set the image views size
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = (int) (width * mHeightRatio);
            setMeasuredDimension(width, height);
        }
        else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="DynamicHeightImageView">
        <attr name="height_ratio" format="float"/>
    </declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)

用法:

<com.melnykov.android.views.DynamicHeightImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scaleType="centerCrop"
    custom:height_ratio="0.6"/>
Run Code Online (Sandbox Code Playgroud)