Last active
May 22, 2018 08:26
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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