在Android中,我定义了一个ImageView的layout_width为fill_parent(它占用了手机的全宽度)。

如果我放入ImageView的图像大于layout_width, Android会缩放?那么高度呢?当Android缩放图像时,它会保持纵横比吗?

我发现在ImageView的顶部和底部有一些空白当Android缩放一个比ImageView大的图像时。这是真的吗?如果是,我如何消除空白?


当前回答

使用android:layout_gravity for ImageView:

android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_weight="1"

上面的例子对我很有用。

其他回答

您可以缩放图像,这也将减少图像的大小。 你可以下载并使用它的库。 https://github.com/niraj124124/Images-Files-scale-and-compress.git

如何使用 1)导入压缩器-v1.0。Jar到您的项目。 2)添加下面的示例代码进行测试。 ResizeLimiter resize = ImageResizer.build(); 调整大小。scale("inputImagePath", "outputImagePath",imageWidth, imageHeight); 根据您的要求,还有更多的方法

你可以计算屏幕宽度。你可以缩放位图。

 public static float getScreenWidth(Activity activity) {
        Display display = activity.getWindowManager().getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        display.getMetrics(outMetrics);
        float pxWidth = outMetrics.widthPixels;
        return pxWidth;
    }

计算屏幕宽度和按屏幕宽度缩放的图像高度。

float screenWidth=getScreenWidth(act)
  float newHeight = screenWidth;
  if (bitmap.getWidth() != 0 && bitmap.getHeight() != 0) {
     newHeight = (screenWidth * bitmap.getHeight()) / bitmap.getWidth();
  }

之后就可以缩放位图了。

Bitmap scaledBitmap=Bitmap.createScaledBitmap(bitmap, (int) screenWidth, (int) newHeight, true);

我有一个算法缩放位图,以最适合容器的尺寸,保持其纵横比。请在这里找到我的解决方案

希望这能帮助到路上的人!

如果图像质量在以下情况下下降: 使用

android:adjustViewBounds="true"

而不是

android:adjustViewBounds="true"
android:scaleType="fitXY"

这是它在ConstraintLayout中为我工作的方式:

<ImageView
    android:id="@+id/myImg"
    android:layout_width="300dp"
    android:layout_height="300dp"
    android:scaleType="fitCenter"
    android:adjustViewBounds="true"/>

然后在代码中,我设置drawable为:

ImageView imgView = findViewById(R.id.myImg);
imgView.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.image_to_show, null));

这很好地符合图像的长宽比,并保持它在中心。