Skip to content

Instantly share code, notes, and snippets.

@rayworks
Last active May 22, 2018 08:26
Show Gist options
  • Save rayworks/c6a71a00219b8d0775940c7d1c33775f to your computer and use it in GitHub Desktop.
Save rayworks/c6a71a00219b8d0775940c7d1c33775f to your computer and use it in GitHub Desktop.
Using scaleType 'Matrix' to implement 'center_crop' or 'left_top aligned crop' effect
public static void setImageMatrixWithRatioKept(
ImageView view, Bitmap resource, boolean scaleByActualWidth, boolean alignmentCenter) {
view.setScaleType(ImageView.ScaleType.MATRIX);
int bmpWidth = resource.getWidth();
int bmpHeight = resource.getHeight();
int viewWidth = view.getWidth();
int viewHeight = view.getHeight();
float scaleWidth = 1.0f * viewWidth / bmpWidth;
float scaleHeight = 1.0f * viewHeight / bmpHeight;
float scale = Math.max(scaleWidth, scaleHeight);
Timber.i(
">>><<< view dimen : w %d | h %d, image resolution : w %d | h %d, "
+ "scaleWidth : %.2f,"
+ " scaleHeight : %.2f",
viewWidth, viewHeight, bmpWidth, bmpHeight, scaleWidth, scaleHeight);
if (scaleByActualWidth) {
scale = scaleWidth;
}
// apply the matrix transformations for the drawable
Matrix matrix = new Matrix();
matrix.setScale(scale, scale);
if (alignmentCenter) {
float dx = -Math.abs(bmpWidth * scale - viewWidth) / 2;
float dy = -Math.abs(bmpHeight * scale - viewHeight) / 2;
matrix.postTranslate(dx, dy);
Timber.w(">>> trans : x %f | y : %f", dx, dy);
}
view.setImageMatrix(matrix);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment