我有一个简单的线性布局用于ListView的单元格,它有一个图像视图。图像将从互联网上下载,因此大小可以不同。
但是,我希望将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>发布于 2013-05-06 19:27:43
您将需要继承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);
}发布于 2013-05-07 17:32:55
从url加载代码中的imageView的位置,您必须在那里设置ImageView的布局参数。它将动态地改变图像的尺寸。
加载图像后,找到尺寸并计算比率,然后根据要应用的条件更改尺寸。
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width,height);
imageView.setLayoutParams(layoutParams);
//set other properties of the imageview according to your conditionhttps://stackoverflow.com/questions/16397753
复制相似问题