I want to scale image to fit screen width and keep aspect ratio
I google for it but set scaleType to FitXY & AdjustViewInBounds doesn't work.
I test with 50x50 image and it's not working
// Use createScaledBitmap will cause OOM, so I set image to imageView first.
ImageView image= (ImageView) mPageView.findViewById(R.id.image);
// Set image to get IntrinsicWidth & IntrinsicHeight
image.setImageResource(imageDrawable);
// Change scale type to matrix
image.setScaleType(ImageView.ScaleType.MATRIX);
// Calculate bottom crop matrix
Matrix matrix = getBottomCropMatrix(mContext, image.getDrawable().getIntrinsicWidth(), image.getDrawable().getIntrinsicHeight());
// Set matrixx
image.setImageMatrix(matrix);
// Redraw image
image_image.invalidate();
And my matrix use following method
Matrix matrix = new Matrix();
// Get screen size
int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
int screenHeight = context.getResources().getDisplayMetrics().heightPixels;
// Get scale to match parent
float scaleWidthRatio = screenWidth / imageWidth;
float scaleHeightRatio = screenHeight / imageHeight;
// screenHeight multi by width scale to get scaled image height
float scaledImageHeight = imageHeight * scaleWidthRatio;
// If scaledImageHeight < screenHeight, set scale to scaleHeightRatio to fit screen
// If scaledImageHeight >= screenHeight, use width scale as height scale
if (scaledImageHeight >= screenHeight) {
scaleHeightRatio = scaleWidthRatio;
}
matrix.setScale(scaleWidthRatio, scaleHeightRatio);
I don't know where I am wrong. It just leave some blank at the bottom.
========
Update. I found out the problem. My matrix is right. The blank at the bottom is soft navigation bar. Use following method will get wrong value.
getResources().getDisplayMetrics()
Change it to
DisplayMetrics displaymetrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getRealMetrics(displaymetrics);
int screenWidth = displaymetrics.widthPixels;
int screenHeight = displaymetrics.heightPixels;
and it works!
Update. I found out the problem. My matrix is right. The blank at the bottom is soft navigation bar. Use following method will get wrong value.
getResources().getDisplayMetrics()
Change it to
DisplayMetrics displaymetrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getRealMetrics(displaymetrics);
int screenWidth = displaymetrics.widthPixels;
int screenHeight = displaymetrics.heightPixels;
and it works!