ImageView 适合宽度裁剪​​底部

ImageView fit width crop bottom

我想缩放图像以适合屏幕宽度并保持纵横比

  1. 如果图像高度小于屏幕高度。我要实力 它。
  2. 如果图像高度大于屏幕高度。我要裁剪它。

我 google 支持它,但将 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:scaleType centerCrop 代替 fitXYmatrix

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="centerCrop" />

更新。我发现了问题。我的矩阵是正确的。底部的空白是软导航栏。使用以下方法会得到错误的值。

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;

而且有效!