如何动态更改ImageView高度

Cul*_*SUN 5 android imageview

我有一个简单的线性布局用于ListView的单元格,它有一个imageview.图像将从互联网上下载,因此尺寸可以是不同的尺寸.

但是,我想将imageview的宽度设置为fill_parent,这是固定的,并在运行时动态更改图像高度.设置图像高度的规则:如果图像的h/w比率大于1,则使ImageView正方形,表示将高度与宽度匹配.

如果图像的h/w比率小于1,则按比例调整大小.预计如下两个样本.

第一个是h/w <1,而第二个'Cat'是h/w> 1.

在此输入图像描述 在此输入图像描述 谢谢你的时间.

    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@color/white"
    android:orientation="vertical"
    android:padding="10dp" >

        <TextView
        android:id="@+id/postTitle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="2"
        android:textColor="@color/black"
        android:textSize="18sp"
        android:textStyle="bold" />

       <ImageView
        android:id="@+id/postImg"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:scaleType="centerCrop"
        android:src="@drawable/dummy_image"
        android:contentDescription="@string/postImage"  />
   </LinearLayout>
Run Code Online (Sandbox Code Playgroud)

Por*_*nny 7

您将需要子类ImageView

覆盖onMeasure,我没有测试过这个,但你需要的所有变量都在那里,这个想法是正确的.您只需执行将图像的纵横比应用于imageviews高度,如果它大于宽度,则将其设置为宽度.

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    Drawable drawable = getDrawable();
    if (drawable != null)
    {
        //get imageview width
        int width =  MeasureSpec.getSize(widthMeasureSpec);


        int diw = drawable.getIntrinsicWidth();
        int dih = drawable.getIntrinsicHeight();
        float ratio = (float)diw/dih; //get image aspect ratio

        int height = width * ratio;

        //don't let height exceed width
        if (height > width){
            height = width;
        }


        setMeasuredDimension(width, height);    
    }
    else
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

}
Run Code Online (Sandbox Code Playgroud)