如何动态更改ImageView的高度

5
我有一个用于ListView单元格的简单线性布局,并且它包含一个ImageView。图片将从互联网下载,因此大小可以不同。
然而,我想将ImageView的宽度设置为fill_parent,即固定的宽度,并在运行时动态更改图像高度。设置图像高度的规则如下:如果图像的高/宽比大于1,则使ImageView正方形,即将其高度与宽度匹配。
如果图像的高/宽比小于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>
2个回答

7

您需要继承ImageView类。

重写onMeasure方法,我尚未测试过,但您需要的所有变量都在那里,想法是正确的。您只需将图像的纵横比应用于ImageView的高度,如果它大于宽度,则将其设置为宽度。

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

}

发生了什么,因为这些设置将缩放图像,使宽度保持不变,而高度则根据图像的纵横比拉伸。 - Pork 'n' Bunny
我展示的XML是用于适配器的getView方法,ImageView会动态从URL加载图像。 - Cullen SUN
实际上我应该问“如何获取fill_parent的实际像素大小”,我通过使用DisplayMetrics解决了这个问题。 - Cullen SUN
做你正在做的事情,你真的不需要那样做... 你能发一下问题的截图吗? - Pork 'n' Bunny
请查看我的回答,这将处理图像的大小。您将不得不尝试使用scaleType来使图像在ImageView中看起来正确。 - Pork 'n' Bunny
显示剩余2条评论

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

我已经有了图片的尺寸。那么问题来了,我怎样知道要为ImageView设置什么高度呢?我是通过displaymetrics.widthPixels减去我在xml布局中设置的边距(dp转px)来实现的。这是最好的方法吗?谢谢。 - Cullen SUN

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接