I have a simple linear layout used for ListView's cell, and it has an imageview. The image will be downloaded from internet, so the size can be different sizes.
However, I want to set the width of imageview to be fill_parent, which is fixed, and dynamically change the image height at runtime. Rules to set the image height: if the image's h/w ratio is more than 1, make the ImageView square, means match the height to the width.
if the image's h/w ratio is less than 1, size it proportionally. Expected two samples as below.
The First one is h/w<1, while the second one 'Cat' is h/w>1.
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>
If you want to just fit the image in image view you can use" wrap content" in height and width property with scale-type but if you want to set manually you have to use LayoutParams. Layoutparams is efficient for setting the layout height and width programmatically.
You will need to subclass ImageView
Override the onMeasure, I haven't tested this but all the variables you need are there and the idea is correct. You just perform the apply the aspect ratio of the image to the imageviews height, and if it's greater than the width, set it to the width.
@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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With