For such tasks, I use this simple class. It matches the height or width, scaling the image properly (it depends on which size is smaller). After this operation, it centers the image within the ImageView.
public class FixedCenterCrop extends ImageView { public FixedCenterCrop(Context context) { super(context); setScaleType(ScaleType.MATRIX); } public FixedCenterCrop(Context context, AttributeSet attrs) { super(context, attrs); setScaleType(ScaleType.MATRIX); } public FixedCenterCrop(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setScaleType(ScaleType.MATRIX); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); recomputeImgMatrix(); } @Override protected boolean setFrame(int l, int t, int r, int b) { recomputeImgMatrix(); return super.setFrame(l, t, r, b); } private void recomputeImgMatrix() { final Matrix matrix = getImageMatrix(); float scale; final int viewWidth = getWidth() - getPaddingLeft() - getPaddingRight(); final int viewHeight = getHeight() - getPaddingTop() - getPaddingBottom(); final int drawableWidth = getDrawable().getIntrinsicWidth(); final int drawableHeight = getDrawable().getIntrinsicHeight(); if (drawableWidth * viewHeight > drawableHeight * viewWidth) { scale = (float) viewHeight / (float) drawableHeight; } else { scale = (float) viewWidth / (float) drawableWidth; } matrix.setScale(scale, scale); matrix.postTranslate((viewWidth - drawableWidth * scale) / 2, (viewHeight - drawableHeight*scale)/2); setImageMatrix(matrix); } }
source share