5

我有一个用于 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>
4

2 回答 2

7

您将需要继承 ImageView

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

@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);

}
于 2013-05-06T11:27:42.673 回答
0

你从url的代码中加载imageView的地方,你必须在那里设置ImageView的布局参数。它将动态更改图像的尺寸。

加载图像后,找到尺寸并计算比例并根据您要应用的条件更改尺寸。

    LinearLayout.LayoutParams layoutParams  = new LinearLayout.LayoutParams(width,height);
    imageView.setLayoutParams(layoutParams);
    //set other properties of the imageview according to your condition
于 2013-05-07T09:32:55.077 回答