user291701
user291701

Reputation: 39681

ImageView android:scaleType, scale up, center vertical, left align?

I have an imageview which will have a fixed size:

layout_width="100dip"
layout_height="50dip"

but the bitmap I want to place in there can be a variable width / height. I'd like to scale the bitmap (maintaining aspect ratio) to fit the 100dip,50dip space. After scaling up, I'd like to center it vertically, and left-align it.

Do any of the predefined imageview android:scaleType flags do that for us?

If not, is the only way to do this to modify the bitmap myself manually (create a canvas at 100dip, 50dip dip size, then place the bitmap in the canvas at the position I want after scaling it up)?

Thanks

Upvotes: 1

Views: 1855

Answers (1)

asenovm
asenovm

Reputation: 6517

You do not need to create a canvas, you can use the imageview's setImageMatrix method instead. Like so:

final Bitmap bitmap = ...;//your bitmap
final int bitmapWidth = bitmap.getWidth();
final int bitmapHeight = bitmap.getHeight();
final float scaleRatio = Math.min(100f/bitmapWidth,50f/bitmapHeight);
final float deltaX = (100 - bitmapWidth * scaleRatio)/2;
final float deltaY = (50 - bitmapHeight * scaleRatio)/2;
final Matrix matrix = new Matrix();
matrix.postScale(scaleRatio,scaleRatio);
matrix.postTranslate(deltaX,deltaY);
imageView.setImageBitmap(bitmap);
imageView.setImageMatrix(matrix);

Upvotes: 1

Related Questions