我有一个用于 ListView 单元格的简单线性布局,它有一个图像视图。图像将从互联网下载,因此尺寸可以不同。
但是,我想将imageview的宽度设置为fill_parent,这是固定的,并在运行时动态改变图像高度。设置图像高度的规则:
如果图像的高宽比大于 1,则将 ImageView 设为正方形,意味着高度与宽度匹配。
如果图像的高宽比小于 1,则按比例调整大小。预计有两个样品如下。
第一个是 h/w1。
Thanks for your time.
<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>
您需要子类化 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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)