Android ImageView 填充父的宽度或高度,但保持纵横比

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10826422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:06:23  来源:igfitidea点击:

ImageView fills parent's width OR height, but maintains aspect ratio

androidandroid-layoutandroid-imageviewandroid-relativelayout

提问by garbagecollector

I have a square image (though this problem also applies to rectangular images). I want to display the image as large as possible, stretching them if necessary, to fill their parents, while still maintaining the aspect ratio. The image is smaller than the ImageView. The problem is, I can't stretch the image and "match" the height and width of the ImageView.

我有一个方形图像(尽管这个问题也适用于矩形图像)。我想显示尽可能大的图像,必要时拉伸它们,以填充它们的父级,同时仍然保持纵横比。图像比 ImageView 小。问题是,我无法拉伸图像并“匹配”ImageView 的高度和宽度。

This is my XML layout file:

这是我的 XML 布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="10dp">

    <ImageView android:id="@+id/image"
               android:layout_width="fill_parent"
               android:layout_height="fill_parent"
               android:adjustViewBounds="true"
               android:scaleType="fitCenter"
               android:layout_marginTop="10dp"/>

    <TextView android:id="@+id/name"
              android:layout_below="@id/image"
              android:layout_alignLeft="@id/image"
              android:layout_marginTop="20dp"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:textSize="18dp"/>

    <TextView android:id="@+id/name2"
              android:layout_below="@id/name"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:textSize="14dp"/>


</RelativeLayout>

I have used many combinations of fill_parent, wrap_contentwith multiple scaleTypes: fitCenter, fitStart, fitEnd, centerInside, and they all draw the images in the right aspect ratio, but none of them actually scale the images up and the ImageView itself, resulting in either the TextViews get pushed all the way down off the screen, blank spaces inside the ImageView, image not scaled, or image cropped.

我使用了多种fill_parent,wrap_content和多个 scaleTypes: fitCenter, fitStart, fitEnd, 的组合centerInside,它们都以正确的纵横比绘制图像,但它们都没有实际放大图像和 ImageView 本身,导致 TextViews 被推到所有远离屏幕、ImageView 内的空白区域、未缩放的图像或裁剪的图像。

I can't quite figure the right combination for this.

我无法完全找到正确的组合。

回答by FoamyGuy

These:

这些:

android:layout_height="wrap_content"
android:scaleType="fitStart"
android:adjustViewBounds="true"

should resize the image and change the size of the bounds to fit the new image size. If it does not do that on your device post the image you are using and what device you are testing on.

应该调整图像大小并更改边界的大小以适应新的图像大小。如果它在您的设备上没有这样做,请发布您正在使用的图像以及您正在测试的设备。

回答by Context

Use this code : android:scaleType="fitXY"

使用此代码: android:scaleType="fitXY"

For more details about image scaling, look what's motioned in this article here

有关图像缩放的更多详细信息,请在此处查看本文中的动作

Summary:

概括:

  • center
  • center

Center the image in the view, but perform no scaling

在视图中居中图像,但不执行缩放

enter image description here

在此处输入图片说明

  • centerCrop
  • centerCrop

Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). The image is then centered in the view

均匀缩放图像(保持图像的纵横比),使图像的两个尺寸(宽度和高度)等于或大于视图的相应尺寸(减去填充)。然后图像在视图中居中

enter image description here

在此处输入图片说明

  • centerInside
  • centerInside

Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding)

统一缩放图像(保持图像的纵横比),使图像的两个尺寸(宽度和高度)等于或小于视图的相应尺寸(减去填充)

enter image description here

在此处输入图片说明

  • fitCenter
  • fitCenter

enter image description here

在此处输入图片说明

  • fitEnd
  • fitEnd

enter image description here

在此处输入图片说明

  • fitStart
  • fitStart

enter image description here

在此处输入图片说明

  • fitXY
  • fitXY

enter image description here

在此处输入图片说明

  • matrix
  • matrix

Scale using the image matrix when drawing

绘制时使用图像矩阵进行缩放

enter image description here

在此处输入图片说明

more details herenew article

更多细节在这里新文章

回答by Febin Mathew

This xml code will work!. If you are specifying that your apps width is always same as the window, then the android:adjustViewBounds="true"will set the height respective to the ration of the image.

此 xml 代码将起作用!。如果您指定应用程序的宽度始终与窗口相同,则将android:adjustViewBounds="true"根据图像的比例设置高度。

        <ImageView
        android:adjustViewBounds="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/screen"/>

回答by akashPatra

Use this code with view layout parameters as wrapcontent

将此代码与视图布局参数一起用作 wrapcontent

android:adjustViewBounds="true"

android:adjustViewBounds="true"

Hope this it will work.

希望这会奏效。

回答by Laurie Trichet

I had the same issue, android:adjustViewBounds not doing its job and having a padding at the top of the image. Into a relative layout that had match_parent values for the width and the height, I had:

我有同样的问题, android:adjustViewBounds 没有完成它的工作并且在图像顶部有一个填充。进入具有 match_parent 宽度和高度值的相对布局,我有:

   <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical" android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="@color/transparent">

   <ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="fitStart"
    android:adjustViewBounds="true" ...

I changed the Relative layout to a Linear layout with wrap_content values for width and height and now it is ok:

我将相对布局更改为带有宽度和高度的 wrap_content 值的线性布局,现在可以了:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

回答by slybloty

Did you try to adjust it programmaticaly? I think it works really well if you calculate the height of your TextViews and adjust the height and width of the image based on this.

您是否尝试以编程方式对其进行调整?我认为如果您计算TextViews 的高度并根据此调整图像的高度和宽度,它会非常有效。

private void adjustImageView()
{
    //Get the display dimensions
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    //TextView name
    TextView name = (TextView) findViewById(R.id.name);
    name.setText("your name text goes here");
    name.measure(0, 0);

    //name TextView height
    int nameH = name.getMeasuredHeight();

    //TextView name2
    TextView name2 = (TextView) findViewById(R.id.name2);
    name2.setText("your name2 text goes here");
    name2.measure(0, 0);

    //name2 TextView height
    int name2H = name2.getMeasuredHeight();

    //Original image
    Bitmap imageOriginal = BitmapFactory.decodeResource(getResources(), R.drawable.image);

    //Width/Height ratio of your image
    float imageOriginalWidthHeightRatio = (float) imageOriginal.getWidth() / (float) imageOriginal.getHeight();

    //Calculate the new width and height of the image to display 
    int imageToShowHeight = metrics.heightPixels - nameH - name2H;
    int imageToShowWidth = (int) (imageOriginalWidthHeightRatio * imageToShowHeight);

    //Adjust the image width and height if bigger than screen
    if(imageToShowWidth > metrics.widthPixels)
    {
        imageToShowWidth = metrics.widthPixels;
        imageToShowHeight = (int) (imageToShowWidth / imageOriginalWidthHeightRatio);
    }

    //Create the new image to be shown using the new dimensions 
    Bitmap imageToShow = Bitmap.createScaledBitmap(imageOriginal, imageToShowWidth, imageToShowHeight, true);

    //Show the image in the ImageView
    ImageView image = (ImageView) findViewById(R.id.image);
    image.setImageBitmap(imageToShow);
}

回答by Fathima km

Set android:layout_height="wrap_content"in imageview. To create an image with width equals screen width, and height proportionally set according to aspect ratio, do the following. Here I mention how to load image to imageview from url.

android:layout_height="wrap_content"在图像视图中设置。要创建宽度等于屏幕宽度且高度根据纵横比按比例设置的图像,请执行以下操作。这里我提到了如何从 url 加载图像到 imageview。

Glide.with(context).load(url).asBitmap().into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                        // creating the image that maintain aspect ratio with width of image is set to screenwidth.
                        int width = imageView.getMeasuredWidth();
                        int diw = resource.getWidth();
                        if (diw > 0) {
                            int height = 0;
                            height = width * resource.getHeight() / diw;
                            resource = Bitmap.createScaledBitmap(resource, width, height, false);
                        }
                                              imageView.setImageBitmap(resource);
                    }
                });

Hope this helps.

希望这可以帮助。