Skip to content

Instantly share code, notes, and snippets.

@suclike
Created December 7, 2015 23:05
Show Gist options
  • Save suclike/a959fd709b069322cc6d to your computer and use it in GitHub Desktop.
Save suclike/a959fd709b069322cc6d to your computer and use it in GitHub Desktop.
import android.content.Context;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.widget.ImageView;
public class TopImageCrop extends ImageView {
public TopImageCrop(final Context context) {
super(context);
init();
}
public TopImageCrop(final Context context, final AttributeSet attrs) {
super(context, attrs);
init();
}
public TopImageCrop(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setScaleType(ImageView.ScaleType.MATRIX);
}
@Override
protected boolean setFrame(final int frameLeft, final int frameTop, final int frameRight, final int frameBottom) {
float frameWidth = frameRight - frameLeft;
float frameHeight = frameBottom - frameTop;
float originalImageWidth = (float) getDrawable().getIntrinsicWidth();
float originalImageHeight = (float) getDrawable().getIntrinsicHeight();
float usedScaleFactor = 1;
if ((originalImageWidth > frameWidth) || (originalImageHeight > frameHeight)) {
// If frame is bigger than image
// => Crop it, keep aspect ratio and position it at the bottom and center horizontally
float fitHorizontallyScaleFactor = frameWidth / originalImageWidth;
float fitVerticallyScaleFactor = frameHeight / originalImageHeight;
usedScaleFactor = Math.max(fitHorizontallyScaleFactor, fitVerticallyScaleFactor);
}
float newImageWidth = originalImageWidth * usedScaleFactor;
float newImageHeight = originalImageHeight * usedScaleFactor;
Matrix matrix = getImageMatrix();
matrix.setScale(usedScaleFactor, usedScaleFactor, 0, 0); // Replaces the old matrix completly
matrix.postTranslate((frameWidth - newImageWidth) / 2, frameHeight - newImageHeight);
setImageMatrix(matrix);
return super.setFrame(frameLeft, frameTop, frameRight, frameBottom);
}
}
@suclike
Copy link
Author

suclike commented Dec 7, 2015

Use with ContextCompat.getDrawable(context, R.drawable.resource)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment