Android ImageView - fill width and resize to maintain aspect ratio

I have a View string that I use in a ListView .

This RowView consists of an ImageView on the left and a TextView on the right in the horizontal LinearLayout , where the image is assigned 40% space and the text is 60%.

I want the layout to handle image resizing in ImageView as follows:

  • Stretch the image horizontally to fill the specified 40% LinearLayout
  • Resize ImageView vertically to maintain original aspect ratio

This is my approach to layouts:

 protected class RowView extends LinearLayout { public ImageView iv = null; public TextView tv = null; private LinearLayout.LayoutParams ivlp = null; private LinearLayout.LayoutParams tvlp = null; public RowView(Context ct) { super(ct); setOrientation(LinearLayout.HORIZONTAL); // Create the views iv = new ImageView(ct); ivlp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.4f); iv.setLayoutParams(ivlp); iv.setAdjustViewBounds(true); iv.setScaleType(ScaleType.FIT_XY); tv = new TextView(ct); tvlp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 0.4f); tv.setLayoutParams(tvlp); tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT); // Add the views addView(iv); addView(tv); } 

}

The result I get looks something like this:

enter image description here

From what I understand:

  • MATCH_PARENT correctly causes the image to stretch horizontally to fill 40% of the space
  • ImageView.setAdjustViewBounds(true) is supposed to allow any ImageView resizing, which is what I want. The problem is that none of ImageView.ScaleType does what I want.
  • ImageView.ScaleType(ScaleType.FIT_XY) not what I want because it does not support aspect ratio. But all the others that do not stretch the height of the ImageView (which makes ImageView.setAdjustViewBounds(true) almost useless).

What am I doing wrong? It seems wrong that something so simple can be so complicated?

Or do I really need to go to the ImageView extension and Overriding onMeasure to force resize and aspect ratio?

Or is there a smart trick with Matrix to get the job done?

+4
source share
2 answers

I believe this is what you are looking for:

 <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/myImage" android:scaleType="fitCenter" android:adjustViewBounds="true" /> 
+3
source

Delete scale type completely. Also, I think you may have misunderstood what setAdjustViewBounds does. If the image is scaled, the bitmap in ImageView scaled, but not ImageView . Setting setAdjustViewBounds to true ensures that the borders of the ImageView will always match the borders of the drawn raster images.

0
source

All Articles