Android Imageview Adjusting Parent's Height and Fitting Width

Android ImageView adjusting parent's height and fitting width

Thanks to @Julien and @js.
Here is complete solution of ImageView that will stretch bitmap height preserving aspect ratio even if bitmap is smaller than ImageView.

public class ResizableImageView extends ImageView {

public ResizableImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
Drawable d = getDrawable();

if(d!=null){
// ceil not round - avoid thin vertical gaps along the left/right edges
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = (int) Math.ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());
setMeasuredDimension(width, height);
}else{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}

}

You can use this class in your xml layouts instead ImageView.

<com.example.ResizableImageView
android:id="@+id/banner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/banner" />

Adjust ImageView width according to height

Add a linear layout on the image view. Just the image view and nothing else. :) hope it helps

EDIT 1: As many of the other answers mentioned Using the layout_weight property will also help resolve this issue.

How to create an ImageView that fills the parent height and displays an Image as big as possible?

Basically the answer here is that there is no predefined value for what you are trying to achieve. The solution is to create a Matrix that fits to your needs and call setImageMatrix(matrix) on your ImageView.

Set width and height based on dimentions of parent's parent Android Studio

It is possible to change a dynamic view's dimensions by code. So I would bet you should change the ImageView's layout parameters in the for loop before adding it to your LinearLayout like this:

for(Object intObj : page.content) {
ImageView imageView = new ImageView(this.getContext());
Drawable myDrawable = getResources().getDrawable((int) intObj);
imageView.setImageDrawable(myDrawable);
//Changing height...
imageView.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
//...and width
imageView.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
scrollViewLayout.addView(imageView);
}

This will set the ImageView's width and height to the containing (parent) LinearLayout's width and height.



Related Topics



Leave a reply



Submit