如何在 ImageView 中缩放图像以保持宽高比

发布于 2024-08-26 20:16:32 字数 346 浏览 9 评论 0原文

在 Android 中,我将 ImageViewlayout_width 定义为 fill_parent (它占据了手机的整个宽度)。

如果我放入 ImageView 的图像大于 layout_width,Android 会缩放它,对吧?但是身高呢?当Android缩放图像时,它会保持宽高比吗?

我发现,当 Android 缩放大于 ImageView 的图像时,ImageView 的顶部和底部会出现一些空白。这是真的吗?如果是,我怎样才能消除那个空白?

In Android, I defined an ImageView's layout_width to be fill_parent (which takes up the full width of the phone).

If the image I put to ImageView is bigger than the layout_width, Android will scale it, right? But what about the height? When Android scales the image, will it keep the aspect ratio?

What I find out is that there is some white space at the top and bottom of the ImageView when Android scales an image which is bigger than the ImageView. Is that true? If yes, how can I eliminate that white space?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(26

○闲身 2024-09-02 20:16:33

您可以计算屏幕宽度。并且您可以缩放位图。

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

You can calculate screen width. And you can scale bitmap.

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

calculate screen width and scaled image height by screen width.

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

After you can scale bitmap.

Bitmap scaledBitmap=Bitmap.createScaledBitmap(bitmap, (int) screenWidth, (int) newHeight, true);
顾北清歌寒 2024-09-02 20:16:33

以编程方式执行此操作时,请确保以正确的顺序调用设置器:

imageView.setAdjustViewBounds(true)
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP)

When doing this programmatically, be sure to call the setters in the correct order:

imageView.setAdjustViewBounds(true)
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP)
梦旅人picnic 2024-09-02 20:16:33

如果您希望图像占据尽可能大的空间,那么最好的选择是

android:layout_weight="1"
android:scaleType="fitCenter"

If you want your image occupy the maximum possible space then the best option would be

android:layout_weight="1"
android:scaleType="fitCenter"
人心善变 2024-09-02 20:16:33

你不需要任何java代码。你只需要:

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

关键在于宽度和高度的匹配父级

Yo don't need any java code. You just have to :

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

The key is in the match parent for width and height

浪推晚风 2024-09-02 20:16:33

我用这个:

<ImageView
android:id="@+id/logo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:scaleType="centerInside"
android:src="@drawable/logo" />

I use this:

<ImageView
android:id="@+id/logo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:scaleType="centerInside"
android:src="@drawable/logo" />
逆光下的微笑 2024-09-02 20:16:33

尝试对 ImageView 使用 android:layout_gravity

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

上面的示例对我有用。

Try using 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"

The example above worked for me.

陌伤浅笑 2024-09-02 20:16:33

我有一种算法可以缩放位图以最适合容器尺寸,同时保持其纵横比。请在此处找到我的解决方案

希望这可以帮助某人车道!

I have an algorithm to scale a bitmap to bestFit the container dimensions, maintaining its aspect ratio. Please find my solution here

Hope this helps someone down the lane!

浅忆 2024-09-02 20:16:33

传递你的 ImageView 并根据屏幕高度和宽度你可以制作它

    public void setScaleImage(EventAssetValueListenerView view){
        // Get the ImageView and its bitmap
        Drawable drawing = view.getDrawable();
        Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();
        // Get current dimensions
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        float xScale = ((float) 4) / width;
        float yScale = ((float) 4) / height;
        float scale = (xScale <= yScale) ? xScale : yScale;

        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);

        Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        BitmapDrawable result = new BitmapDrawable(scaledBitmap);
        width = scaledBitmap.getWidth();
        height = scaledBitmap.getHeight();

        view.setImageDrawable(result);

        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
        params.width = width;
        params.height = height;
        view.setLayoutParams(params);
    }

Pass your ImageView and based on screen height and width you can make it

    public void setScaleImage(EventAssetValueListenerView view){
        // Get the ImageView and its bitmap
        Drawable drawing = view.getDrawable();
        Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();
        // Get current dimensions
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        float xScale = ((float) 4) / width;
        float yScale = ((float) 4) / height;
        float scale = (xScale <= yScale) ? xScale : yScale;

        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);

        Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        BitmapDrawable result = new BitmapDrawable(scaledBitmap);
        width = scaledBitmap.getWidth();
        height = scaledBitmap.getHeight();

        view.setImageDrawable(result);

        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
        params.width = width;
        params.height = height;
        view.setLayoutParams(params);
    }

記憶穿過時間隧道 2024-09-02 20:16:33

以编程方式将宽高比应用于图像视图:

aspectRatio = imageWidth/imageHeight   
ratioOfWidth = imageWidth/maxWidth  
ratioOfHeight = imageHeight/maxHeight  


if(ratioOfWidth > ratioOfHeight){​​​​​​​
    imageWidth = maxWidth 
    imageHeight = imageWidth/aspectRatio
}​​​​​​​ else if(ratioOfHeight > ratioOfWidth){​​​​​​​
    imageHeight = maxHeight
    imageWidth = imageHeight * aspectRatio
}​​​​​​​

之后,您可以使用缩放的位图来图像视图

Bitmap scaledBitmap= Bitmap.createScaledBitmap(bitmap, (int) imageWidth , (int) imageHeight , true);

Programatically apply aspect ratio to Imageview:

aspectRatio = imageWidth/imageHeight   
ratioOfWidth = imageWidth/maxWidth  
ratioOfHeight = imageHeight/maxHeight  


if(ratioOfWidth > ratioOfHeight){​​​​​​​
    imageWidth = maxWidth 
    imageHeight = imageWidth/aspectRatio
}​​​​​​​ else if(ratioOfHeight > ratioOfWidth){​​​​​​​
    imageHeight = maxHeight
    imageWidth = imageHeight * aspectRatio
}​​​​​​​

After that you can use scaled bitmap to image view

Bitmap scaledBitmap= Bitmap.createScaledBitmap(bitmap, (int) imageWidth , (int) imageHeight , true);
梦里泪两行 2024-09-02 20:16:33

如果使用 cardview 进行舍入 imageview 并修复 android:layout_height 标题,这对我来说可以使用 Glide 加载图像代码>

    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="220dp"
             xmlns:card_view="http://schemas.android.com/apk/res-auto"
             >

    <android.support.v7.widget.CardView
            android:id="@+id/card_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center|top"
            card_view:cardBackgroundColor="@color/colorPrimary"
            card_view:cardCornerRadius="10dp"
            card_view:cardElevation="10dp"
            card_view:cardPreventCornerOverlap="false"
            card_view:cardUseCompatPadding="true">

        <ImageView
                android:adjustViewBounds="true"
                android:maxHeight="220dp"
                android:id="@+id/iv_full"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:scaleType="fitCenter"/>

    </android.support.v7.widget.CardView>
</FrameLayout>

in case of using cardviewfor rounding imageview and fixed android:layout_height for header this worked for me to load image with Glide

    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="220dp"
             xmlns:card_view="http://schemas.android.com/apk/res-auto"
             >

    <android.support.v7.widget.CardView
            android:id="@+id/card_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center|top"
            card_view:cardBackgroundColor="@color/colorPrimary"
            card_view:cardCornerRadius="10dp"
            card_view:cardElevation="10dp"
            card_view:cardPreventCornerOverlap="false"
            card_view:cardUseCompatPadding="true">

        <ImageView
                android:adjustViewBounds="true"
                android:maxHeight="220dp"
                android:id="@+id/iv_full"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:scaleType="fitCenter"/>

    </android.support.v7.widget.CardView>
</FrameLayout>
南街女流氓 2024-09-02 20:16:33

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

使用方法
1)导入压缩机-v1.0。 jar 到您的项目中。
2)添加以下示例代码进行测试。
ResizeLimiter 调整大小 = ImageResizer.build();
resize.scale("inputImagePath", "outputImagePath",imageWidth, imageHeight);
还有很多方法可以根据你的需求

You can scale image that will also reduce the size of your image.
There is a library for it you can download and use it.
https://github.com/niraj124124/Images-Files-scale-and-compress.git

How to use
1)Import the compressor-v1.0. jar to your project.
2)Add the below sample code to test.
ResizeLimiter resize = ImageResizer.build();
resize.scale("inputImagePath", "outputImagePath",imageWidth, imageHeight);
Many more methods are there according to your requirement

过度放纵 2024-09-02 20:16:33

快速回答:

<ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="center"
        android:src="@drawable/yourImage"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Quick answer:

<ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="center"
        android:src="@drawable/yourImage"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
陪我终i 2024-09-02 20:16:33
imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 130, 110, false));
imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 130, 110, false));
兰花执着 2024-09-02 20:16:32
  1. 是的,默认情况下 Android 会缩小图像以适合 ImageView,同时保持宽高比。但是,请确保使用 android:src="..." 而不是 android:background="..." 将图像设置为 ImageView。 src= 使其缩放图像保持纵横比,但 background= 使其缩放扭曲图像以使其完全适合尺寸ImageView 的。 (不过,您可以同时使用背景和源,这对于仅使用一个 ImageView 在主图像周围显示框架之类的事情很有用。)

  2. 您还应该看到 android:adjustViewBounds< /code> 使 ImageView 调整自身大小以适应重新缩放的图像。例如,如果您在通常为方形 ImageView 中有一个矩形图像,则 adjustmentViewBounds=true 也会将 ImageView 的大小调整为矩形。这会影响 ImageView 周围其他视图的布局方式。

    然后,正如 Samuh 所写,您可以使用 android:scaleType 参数更改默认缩放图像的方式。顺便说一句,了解其工作原理的最简单方法就是自己进行一些实验!请记住查看模拟器本身(或实际手机)中的布局,因为 Eclipse 中的预览通常是错误的。

  1. Yes, by default Android will scale your image down to fit the ImageView, maintaining the aspect ratio. However, make sure you're setting the image to the ImageView using android:src="..." rather than android:background="...". src= makes it scale the image maintaining aspect ratio, but background= makes it scale and distort the image to make it fit exactly to the size of the ImageView. (You can use a background and a source at the same time though, which can be useful for things like displaying a frame around the main image, using just one ImageView.)

  2. You should also see android:adjustViewBounds to make the ImageView resize itself to fit the rescaled image. For example, if you have a rectangular image in what would normally be a square ImageView, adjustViewBounds=true will make it resize the ImageView to be rectangular as well. This then affects how other Views are laid out around the ImageView.

    Then as Samuh wrote, you can change the way it default scales images using the android:scaleType parameter. By the way, the easiest way to discover how this works would simply have been to experiment a bit yourself! Just remember to look at the layouts in the emulator itself (or an actual phone) as the preview in Eclipse is usually wrong.

无法回应 2024-09-02 20:16:32

请参阅 android:adjustViewBounds

如果您希望 ImageView 调整其边界以保留其可绘制的纵横比,请将此项设置为 true。

See android:adjustViewBounds.

Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable.

凉城 2024-09-02 20:16:32

对于任何其他遇到此特定问题的人。您有一个 ImageView,您希望其宽度为 fill_parent 且高度按比例缩放:

将这两个属性添加到您的 ImageView 中:

android:adjustViewBounds="true"
android:scaleType="centerCrop"

并设置将 ImageView 宽度设置为 fill_parent,将高度设置为 wrap_content

另外,如果您不想裁剪图像,请尝试以下操作:

 android:adjustViewBounds="true"
 android:layout_centerInParent="true"

To anyone else having this particular issue. You have an ImageView that you want to have a width of fill_parent and a height scaled proportionately:

Add these two attributes to your ImageView:

android:adjustViewBounds="true"
android:scaleType="centerCrop"

And set the ImageView width to fill_parent and height to wrap_content.

Also, if you don't want your image to be cropped, try this:

 android:adjustViewBounds="true"
 android:layout_centerInParent="true"
肩上的翅膀 2024-09-02 20:16:32

如果您想要一个在保持适当的宽高比的同时放大和缩小的 ImageView ,请将其添加到您的 XML 中:

android:adjustViewBounds="true"
android:scaleType="fitCenter"

将其添加到您的代码中:

// We need to adjust the height if the width of the bitmap is
// smaller than the view width, otherwise the image will be boxed.
final double viewWidthToBitmapWidthRatio = (double)image.getWidth() / (double)bitmap.getWidth();
image.getLayoutParams().height = (int) (bitmap.getHeight() * viewWidthToBitmapWidthRatio);

我花了一段时间才使其正常工作,但出现了在图像小于屏幕宽度和大于屏幕宽度的情况下工作,并且不会对图像进行装箱。

If you want an ImageView that both scales up and down while keeping the proper aspect ratio, add this to your XML:

android:adjustViewBounds="true"
android:scaleType="fitCenter"

Add this to your code:

// We need to adjust the height if the width of the bitmap is
// smaller than the view width, otherwise the image will be boxed.
final double viewWidthToBitmapWidthRatio = (double)image.getWidth() / (double)bitmap.getWidth();
image.getLayoutParams().height = (int) (bitmap.getHeight() * viewWidthToBitmapWidthRatio);

It took me a while to get this working, but this appears to work in the cases both where the image is smaller than the screen width and larger than the screen width, and it does not box the image.

豆芽 2024-09-02 20:16:32

这对我有用:

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="39dip"
android:scaleType="centerCrop"
android:adjustViewBounds ="true"

This worked for me:

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="39dip"
android:scaleType="centerCrop"
android:adjustViewBounds ="true"
蓝天白云 2024-09-02 20:16:32

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

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

然后在代码中,我将可绘制对象设置为:

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

这根据图像的长宽比很好地适合图像并将其保持在中心。

This is how it worked for me inside a ConstraintLayout:

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

Then in code, I set the drawable as:

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

This fits the image nicely according to its aspect ratio and keeps it in centre.

寻找我们的幸福 2024-09-02 20:16:32

这解决了我的问题

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

this solved my problem

android:adjustViewBounds="true"
android:scaleType="fitXY"
南渊 2024-09-02 20:16:32

看一下ImageView.ScaleType控制和理解方式调整大小发生在 ImageView 中。当调整图像大小(同时保持其纵横比)时,图像的高度或宽度可能会小于 ImageView 的尺寸。

Take a look at ImageView.ScaleType to control and understand the way resizing happens in an ImageView. When the image is resized (while maintaining its aspect ratio), chances are that either the image's height or width becomes smaller than ImageView's dimensions.

海的爱人是光 2024-09-02 20:16:32

下面的代码适用于缩放图像作为纵横比:

Bitmap bitmapImage = BitmapFactory.decodeFile("Your path");
int nh = (int) ( bitmapImage.getHeight() * (512.0 / bitmapImage.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(bitmapImage, 512, nh, true);
your_imageview.setImageBitmap(scaled);

Below code Working for scale image as aspect ratio:

Bitmap bitmapImage = BitmapFactory.decodeFile("Your path");
int nh = (int) ( bitmapImage.getHeight() * (512.0 / bitmapImage.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(bitmapImage, 512, nh, true);
your_imageview.setImageBitmap(scaled);
夜访吸血鬼 2024-09-02 20:16:32

在 ImageView 中使用这些属性来保持纵横比:

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

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"
    />

Use these properties in ImageView to keep aspect ratio:

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

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"
    />
﹂绝世的画 2024-09-02 20:16:32

我有一个比屏幕小的图像。为了让它按比例拉伸到最大值并在视图中居中,我必须使用以下代码:

<ImageView
    android:id="@+id/my_image"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerInParent="true"
    android:adjustViewBounds="true"
    android:layout_weight="1"
    android:scaleType="fitCenter" />

但是请记住,如果您有一个相对布局并且将某些元素设置为位于 ImageView 之上或之下,那么它们将是最重要的可能与图像重叠。

I have an image smaller than the screen. To have it stretched proportionally to the max and centered in the view I had to use the following code:

<ImageView
    android:id="@+id/my_image"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_centerInParent="true"
    android:adjustViewBounds="true"
    android:layout_weight="1"
    android:scaleType="fitCenter" />

Have in mind though, that if you have a relative layout and have some elements set to be above or below the ImageView, they will be most likely overlapped by the image.

话少情深 2024-09-02 20:16:32

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

android:adjustViewBounds="true"

而不是

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

If image quality decreases in:
use

android:adjustViewBounds="true"

instead of

android:adjustViewBounds="true"
android:scaleType="fitXY"
迷荒 2024-09-02 20:16:32

对于任何希望图像通过适当的缩放完全适合 imageview 且无需裁剪的人,请使用

imageView.setScaleType(ScaleType.FIT_XY);

imageView 是代表 ImageView 的视图

For anyone of you who wants the image to fit exact the imageview with proper scaling and no cropping use

imageView.setScaleType(ScaleType.FIT_XY);

where imageView is the view representing your ImageView

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文