gpt4 book ai didi

android - ImageView 适合宽度裁剪​​底部

转载 作者:行者123 更新时间:2023-11-29 01:04:32 24 4
gpt4 key购买 nike

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

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

我用谷歌搜索但将 scaleType 设置为 FitXY & AdjustViewInBounds 不起作用。

我用 50x50 的图像进行测试,但它不起作用

enter image description here

// 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;

而且有效!

最佳答案

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

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 - ImageView 适合宽度裁剪​​底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48274598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com