首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何动态更改ImageView高度

如何动态更改ImageView高度
EN

Stack Overflow用户
提问于 2013-05-06 19:25:12
回答 2查看 16.7K关注 0票数 5

我有一个简单的线性布局用于ListView的单元格,它有一个图像视图。图像将从互联网上下载,因此大小可以不同。

但是,我希望将imageview的宽度设置为fill_parent,这是固定的,并在运行时动态更改图像高度。设置图像高度的规则:如果图像的长宽比大于1,则将ImageView设置为正方形,即使图像的高度与宽度匹配。

如果图像的长宽比小于1,则按比例调整大小。预期有两个示例,如下所示。

第一个是h/w<1,第二个'Cat‘是h/w>1。

耽误您时间,实在对不起。

代码语言:javascript
复制
    <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>
EN

回答 2

Stack Overflow用户

发布于 2013-05-06 19:27:43

您将需要继承ImageView的子类

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

代码语言:javascript
复制
@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);

}
票数 7
EN

Stack Overflow用户

发布于 2013-05-07 17:32:55

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

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

代码语言:javascript
复制
    LinearLayout.LayoutParams layoutParams  = new LinearLayout.LayoutParams(width,height);
    imageView.setLayoutParams(layoutParams);
    //set other properties of the imageview according to your condition
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16397753

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档