【发布时间】:2018-01-16 05:25:26
【问题描述】:
我想缩放图像以适应屏幕宽度并保持纵横比
- 如果图像高度小于屏幕高度。我要坚强 它。
- 如果图像高度大于屏幕高度。我想裁剪它。
我用谷歌搜索它,但将 scaleType 设置为 FitXY & AdjustViewInBounds 不起作用。
我用 50x50 的图像进行测试,但它不起作用
// 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();
我的矩阵使用以下方法
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);
我不知道我错在哪里。它只是在底部留下一些空白。
========
更新。我发现了问题。我的矩阵是正确的。底部的空白是软导航栏。使用下面的方法会得到错误的值。
getResources().getDisplayMetrics()
改成
DisplayMetrics displaymetrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getRealMetrics(displaymetrics);
int screenWidth = displaymetrics.widthPixels;
int screenHeight = displaymetrics.heightPixels;
它有效!
【问题讨论】:
标签: android matrix imageview scaletype