WeVie
WeVie

Reputation: 598

Resize image to fit into LinearLayout

I need to dynamically add some images to a LinearLayout based on what the user selects but I cannot figure out how to resize the images before adding them. I have tried the setWidth() and setHeight() methods but it seems to do nothing. I would like to set them to a certain dp.

Thanks to anyone looking at this.

 ImageView image = new ImageView(getApplicationContext());

 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
               LinearLayout.LayoutParams.MATCH_PARENT,
               LinearLayout.LayoutParams.MATCH_PARENT);

image.setLayoutParams(params);
image.setScaleType(ImageView.ScaleType.CENTER);

image.setImageResource(R.drawable.icon1);

LinearLayout layout = (LinearLayout) findViewById(R.id.iconLayout);
layout.addView(image, cart.size()-1, params);

Upvotes: 2

Views: 483

Answers (2)

WeVie
WeVie

Reputation: 598

OK. I figured it out thanks to being steered in the correct direction. I was able to use FIT_CENTER and that done it.

Upvotes: 1

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

problem:

ImageView.ScaleType.CENTER

What it is doing is that it will scale your image but it will only fit on either x or y axis.

from documentation:

Compute a scale that will maintain the original src aspect ratio, 
but will also ensure that src fits entirely inside dst. At least 
one axis (X or Y) will fit exactly. The result is centered inside dst.

solution:

You can use the ImageView.ScaleType.FILL to scale your image in x and y axis depends on the height and width of your ImageView.

image.setScaleType(ImageView.ScaleType.FILL);

Upvotes: 1

Related Questions