Skip to content

Instantly share code, notes, and snippets.

@gitanuj
Created February 22, 2015 15:31
Show Gist options
  • Save gitanuj/686baa89bd19ecc20b7b to your computer and use it in GitHub Desktop.
Save gitanuj/686baa89bd19ecc20b7b to your computer and use it in GitHub Desktop.
Android ImageView which scales the bitmap to fit in a center-bottom manner
import android.content.Context;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* This ImageView scales the image to match either the width or height of the
* ImageView and places in the center-bottom. For eg. if the ImageView is 10x6
* units and the image is 4x4 units, it will scale the image to 6x6 units and
* place as follows:
*
* ++------++ <br>
* ++------++ <br>
* ++------++ <br>
* ++------++ <br>
* ++------++ <br>
* ++------++ <br>
*
* + denotes the blank space in ImageView <br>
* - denotes the image itself
*/
public class CenterBottomImageView extends ImageView {
public CenterBottomImageView(Context context) {
super(context);
setup();
}
public CenterBottomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
setup();
}
public CenterBottomImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setup();
}
private void setup() {
setScaleType(ScaleType.MATRIX);
}
@Override
protected boolean setFrame(int frameLeft, int frameTop, int frameRight, int frameBottom) {
if (getDrawable() != null) {
float frameWidth = frameRight - frameLeft;
float frameHeight = frameBottom - frameTop;
float originalImageWidth = getDrawable().getIntrinsicWidth();
float originalImageHeight = getDrawable().getIntrinsicHeight();
float fitHorizontallyScaleFactor = frameWidth / originalImageWidth;
float fitVerticallyScaleFactor = frameHeight / originalImageHeight;
float usedScaleFactor = Math.min(fitHorizontallyScaleFactor, fitVerticallyScaleFactor);
float newImageWidth = originalImageWidth * usedScaleFactor;
float newImageHeight = originalImageHeight * usedScaleFactor;
Matrix matrix = getImageMatrix();
matrix.setScale(usedScaleFactor, usedScaleFactor, 0, 0);
matrix.postTranslate((frameWidth - newImageWidth) / 2, frameHeight - newImageHeight);
setImageMatrix(matrix);
}
return super.setFrame(frameLeft, frameTop, frameRight, frameBottom);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment