将图像适合 ImageView,保持宽高比,然后将 ImageView 调整为图像尺寸?

发布于 2024-12-17 15:08:47 字数 703 浏览 4 评论 0原文

如何使随机大小的图像适合 ImageView
何时:

  • 最初 ImageView 尺寸为 250dp * 250dp
  • 图像的较大尺寸应向上/向下缩放至 250dp
  • 图像应保持其纵横比
  • ImageView 尺寸应与缩放后的图像尺寸相匹配 后

缩放 对于 100*150 的图像,图像和 ImageView 应为 166*250。
例如,对于 150*100 的图像,图像和 ImageView 应为 250*166。

如果我将边界设置为

<ImageView
    android:id="@+id/picture"
    android:layout_width="250dp"
    android:layout_height="250dp"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="20dp"
    android:adjustViewBounds="true" />

图像适合 ImageView,但 ImageView 始终为 250dp * 250dp。

How to fit an image of random size to an ImageView?
When:

  • Initially ImageView dimensions are 250dp * 250dp
  • The image's larger dimension should be scaled up/down to 250dp
  • The image should keep its aspect ratio
  • The ImageView dimensions should match scaled image's dimensions after scaling

E.g. for an image of 100*150, the image and the ImageView should be 166*250.
E.g. for an image of 150*100, the image and the ImageView should be 250*166.

If I set the bounds as

<ImageView
    android:id="@+id/picture"
    android:layout_width="250dp"
    android:layout_height="250dp"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="20dp"
    android:adjustViewBounds="true" />

images fit properly in the ImageView, but the ImageView is always 250dp * 250dp.

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

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

发布评论

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

评论(21

草莓酥 2024-12-24 15:08:47

可能不是这个特定问题的答案,但如果有人像我一样正在寻找答案,如何在 ImageView 中以有限的尺寸(例如,maxWidth)调整图像,同时保留宽高比,然后摆脱如果 ImageView 占用的空间过多,那么最简单的解决方案是在 XML 中使用以下属性:

    android:scaleType="centerInside"
    android:adjustViewBounds="true"

May not be answer for this specific question, but if someone is, like me, searching for answer how to fit image in ImageView with bounded size (for example, maxWidth) while preserving Aspect Ratio and then get rid of excessive space occupied by ImageView, then the simplest solution is to use the following properties in XML:

    android:scaleType="centerInside"
    android:adjustViewBounds="true"
桃酥萝莉 2024-12-24 15:08:47

(在澄清原始问题后对答案进行了大量修改)

澄清后:
不能仅在 xml 中完成。无法同时缩放图像和 ImageView,以便图像的一维始终为 250dp,并且 ImageView 与图像具有相同的尺寸。

此代码缩放 ImageViewDrawable 以保持在 250dp x 250dp 等正方形中,一维恰好为 250dp 并保持纵横比。然后调整 ImageView 的大小以匹配缩放图像的尺寸。该代码在活动中使用。我通过按钮单击处理程序测试了它。

享受吧。 :)

private void scaleImage(ImageView view) throws NoSuchElementException  {
    // Get bitmap from the the ImageView.
    Bitmap bitmap = null;

    try {
        Drawable drawing = view.getDrawable();
        bitmap = ((BitmapDrawable) drawing).getBitmap();
    } catch (NullPointerException e) {
        throw new NoSuchElementException("No drawable on given view");
    } catch (ClassCastException e) {
        // Check bitmap is Ion drawable
        bitmap = Ion.with(view).getBitmap();
    }

    // Get current dimensions AND the desired bounding box
    int width = 0;

    try {
        width = bitmap.getWidth();
    } catch (NullPointerException e) {
        throw new NoSuchElementException("Can't find bitmap on given view/drawable");
    }

    int height = bitmap.getHeight();
    int bounding = dpToPx(250);
    Log.i("Test", "original width = " + Integer.toString(width));
    Log.i("Test", "original height = " + Integer.toString(height));
    Log.i("Test", "bounding = " + Integer.toString(bounding));

    // Determine how much to scale: the dimension requiring less scaling is
    // closer to the its side. This way the image always stays inside your
    // bounding box AND either x/y axis touches it.  
    float xScale = ((float) bounding) / width;
    float yScale = ((float) bounding) / height;
    float scale = (xScale <= yScale) ? xScale : yScale;
    Log.i("Test", "xScale = " + Float.toString(xScale));
    Log.i("Test", "yScale = " + Float.toString(yScale));
    Log.i("Test", "scale = " + Float.toString(scale));

    // Create a matrix for the scaling and add the scaling data
    Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);

    // Create a new bitmap and convert it to a format understood by the ImageView 
    Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    width = scaledBitmap.getWidth(); // re-use
    height = scaledBitmap.getHeight(); // re-use
    BitmapDrawable result = new BitmapDrawable(scaledBitmap);
    Log.i("Test", "scaled width = " + Integer.toString(width));
    Log.i("Test", "scaled height = " + Integer.toString(height));

    // Apply the scaled bitmap
    view.setImageDrawable(result);

    // Now change ImageView's dimensions to match the scaled image
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); 
    params.width = width;
    params.height = height;
    view.setLayoutParams(params);

    Log.i("Test", "done");
}

private int dpToPx(int dp) {
    float density = getApplicationContext().getResources().getDisplayMetrics().density;
    return Math.round((float)dp * density);
}

ImageView 的 xml 代码:

<ImageView a:id="@+id/image_box"
    a:background="#ff0000"
    a:src="@drawable/star"
    a:layout_width="wrap_content"
    a:layout_height="wrap_content"
    a:layout_marginTop="20dp"
    a:layout_gravity="center_horizontal"/>

感谢有关缩放代码的讨论:
http://www.anddev.org/resize_and_rotate_image_-_example-t621.html

2012 年 11 月 7 日更新:
按照评论中的建议添加了空指针检查

(The answer was heavily modified after clarifications to the original question)

After clarifications:
This cannot be done in xml only. It is not possible to scale both the image and the ImageView so that image's one dimension would always be 250dp and the ImageView would have the same dimensions as the image.

This code scales Drawable of an ImageView to stay in a square like 250dp x 250dp with one dimension exactly 250dp and keeping the aspect ratio. Then the ImageView is resized to match the dimensions of the scaled image. The code is used in an activity. I tested it via button click handler.

Enjoy. :)

private void scaleImage(ImageView view) throws NoSuchElementException  {
    // Get bitmap from the the ImageView.
    Bitmap bitmap = null;

    try {
        Drawable drawing = view.getDrawable();
        bitmap = ((BitmapDrawable) drawing).getBitmap();
    } catch (NullPointerException e) {
        throw new NoSuchElementException("No drawable on given view");
    } catch (ClassCastException e) {
        // Check bitmap is Ion drawable
        bitmap = Ion.with(view).getBitmap();
    }

    // Get current dimensions AND the desired bounding box
    int width = 0;

    try {
        width = bitmap.getWidth();
    } catch (NullPointerException e) {
        throw new NoSuchElementException("Can't find bitmap on given view/drawable");
    }

    int height = bitmap.getHeight();
    int bounding = dpToPx(250);
    Log.i("Test", "original width = " + Integer.toString(width));
    Log.i("Test", "original height = " + Integer.toString(height));
    Log.i("Test", "bounding = " + Integer.toString(bounding));

    // Determine how much to scale: the dimension requiring less scaling is
    // closer to the its side. This way the image always stays inside your
    // bounding box AND either x/y axis touches it.  
    float xScale = ((float) bounding) / width;
    float yScale = ((float) bounding) / height;
    float scale = (xScale <= yScale) ? xScale : yScale;
    Log.i("Test", "xScale = " + Float.toString(xScale));
    Log.i("Test", "yScale = " + Float.toString(yScale));
    Log.i("Test", "scale = " + Float.toString(scale));

    // Create a matrix for the scaling and add the scaling data
    Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);

    // Create a new bitmap and convert it to a format understood by the ImageView 
    Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    width = scaledBitmap.getWidth(); // re-use
    height = scaledBitmap.getHeight(); // re-use
    BitmapDrawable result = new BitmapDrawable(scaledBitmap);
    Log.i("Test", "scaled width = " + Integer.toString(width));
    Log.i("Test", "scaled height = " + Integer.toString(height));

    // Apply the scaled bitmap
    view.setImageDrawable(result);

    // Now change ImageView's dimensions to match the scaled image
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams(); 
    params.width = width;
    params.height = height;
    view.setLayoutParams(params);

    Log.i("Test", "done");
}

private int dpToPx(int dp) {
    float density = getApplicationContext().getResources().getDisplayMetrics().density;
    return Math.round((float)dp * density);
}

The xml code for the ImageView:

<ImageView a:id="@+id/image_box"
    a:background="#ff0000"
    a:src="@drawable/star"
    a:layout_width="wrap_content"
    a:layout_height="wrap_content"
    a:layout_marginTop="20dp"
    a:layout_gravity="center_horizontal"/>

Thanks to this discussion for the scaling code:
http://www.anddev.org/resize_and_rotate_image_-_example-t621.html

UPDATE 7th, November 2012:
Added null pointer check as suggested in comments

乱世争霸 2024-12-24 15:08:47
<ImageView android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:scaleType="centerCrop"
           android:adjustViewBounds="true"/>
<ImageView android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:scaleType="centerCrop"
           android:adjustViewBounds="true"/>
苦妄 2024-12-24 15:08:47

下面的代码使位图与图像视图的大小完美一致。获取位图图像的高度和宽度,然后借助 imageview 的参数计算新的高度和宽度。这为您提供了具有最佳纵横比的所需图像。

int currentBitmapWidth = bitMap.getWidth();
int currentBitmapHeight = bitMap.getHeight();

int ivWidth = imageView.getWidth();
int ivHeight = imageView.getHeight();
int newWidth = ivWidth;

newHeight = (int) Math.floor((double) currentBitmapHeight *( (double) new_width / (double) currentBitmapWidth));

Bitmap newbitMap = Bitmap.createScaledBitmap(bitMap, newWidth, newHeight, true);

imageView.setImageBitmap(newbitMap)

享受。

The Below code make the bitmap perfectly with same size of the imageview. Get the bitmap image height and width and then calculate the new height and width with the help of imageview's parameters. That give you required image with best aspect ratio.

int currentBitmapWidth = bitMap.getWidth();
int currentBitmapHeight = bitMap.getHeight();

int ivWidth = imageView.getWidth();
int ivHeight = imageView.getHeight();
int newWidth = ivWidth;

newHeight = (int) Math.floor((double) currentBitmapHeight *( (double) new_width / (double) currentBitmapWidth));

Bitmap newbitMap = Bitmap.createScaledBitmap(bitMap, newWidth, newHeight, true);

imageView.setImageBitmap(newbitMap)

enjoy.

狠疯拽 2024-12-24 15:08:47

尝试将 android:scaleType="fitXY" 添加到您的 ImageView 中。

try adding android:scaleType="fitXY" to your ImageView.

分分钟 2024-12-24 15:08:47

这一切都可以使用 XML 来完成...其他方法看起来相当复杂。
不管怎样,你只需将高度设置为你想要的 dp 值,然后设置宽度以包裹内容,反之亦然。使用scaleType fitCenter调整图像的大小。

<ImageView
    android:layout_height="200dp"
    android:layout_width="wrap_content"
    android:scaleType="fitCenter"
    android:adjustViewBounds="true"
    android:src="@mipmap/ic_launcher"
    android:layout_below="@+id/title"
    android:layout_margin="5dip"
    android:id="@+id/imageView1">

this can all be done using XML... the other methods seem pretty complicated.
Anyway, you just set the height to what ever you want in dp, then set the width to wrap content or visa versa. Use scaleType fitCenter to adjust the size of the image.

<ImageView
    android:layout_height="200dp"
    android:layout_width="wrap_content"
    android:scaleType="fitCenter"
    android:adjustViewBounds="true"
    android:src="@mipmap/ic_launcher"
    android:layout_below="@+id/title"
    android:layout_margin="5dip"
    android:id="@+id/imageView1">
野心澎湃 2024-12-24 15:08:47

在大多数情况下有效的最佳解决方案是

以下示例:

<ImageView android:id="@+id/avatar"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:scaleType="fitXY"/>

The Best solution that works in most cases is

Here is an example:

<ImageView android:id="@+id/avatar"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:scaleType="fitXY"/>
貪欢 2024-12-24 15:08:47

经过一天的搜索,我认为这是最简单的解决方案:

imageView.getLayoutParams().width = 250;
imageView.getLayoutParams().height = 250;
imageView.setAdjustViewBounds(true);

After searching for a day, I think this is the easiest solution:

imageView.getLayoutParams().width = 250;
imageView.getLayoutParams().height = 250;
imageView.setAdjustViewBounds(true);
半岛未凉 2024-12-24 15:08:47

编辑Jarno Argillanders答案:

如何使图像适合您的宽度和高度:

1) 初始化 ImageView 并设置图像:

iv = (ImageView) findViewById(R.id.iv_image);
iv.setImageBitmap(image);

2) 现在调整大小:

scaleImage(iv);

编辑 scaleImage 方法:(您可以替换预期的边界值

private void scaleImage(ImageView view) {
    Drawable drawing = view.getDrawable();
    if (drawing == null) {
        return;
    }
    Bitmap bitmap = ((BitmapDrawable) drawing).getBitmap();

    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    int xBounding = ((View) view.getParent()).getWidth();//EXPECTED WIDTH
    int yBounding = ((View) view.getParent()).getHeight();//EXPECTED HEIGHT

    float xScale = ((float) xBounding) / width;
    float yScale = ((float) yBounding) / height;

    Matrix matrix = new Matrix();
    matrix.postScale(xScale, yScale);

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

    view.setImageDrawable(result);

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

和 . xml:

<ImageView
    android:id="@+id/iv_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal" />

Edited Jarno Argillanders answer:

How to fit Image with your Width and Height:

1) Initialize ImageView and set Image:

iv = (ImageView) findViewById(R.id.iv_image);
iv.setImageBitmap(image);

2) Now resize:

scaleImage(iv);

Edited scaleImage method: (you can replace EXPECTED bounding values)

private void scaleImage(ImageView view) {
    Drawable drawing = view.getDrawable();
    if (drawing == null) {
        return;
    }
    Bitmap bitmap = ((BitmapDrawable) drawing).getBitmap();

    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    int xBounding = ((View) view.getParent()).getWidth();//EXPECTED WIDTH
    int yBounding = ((View) view.getParent()).getHeight();//EXPECTED HEIGHT

    float xScale = ((float) xBounding) / width;
    float yScale = ((float) yBounding) / height;

    Matrix matrix = new Matrix();
    matrix.postScale(xScale, yScale);

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

    view.setImageDrawable(result);

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

And .xml:

<ImageView
    android:id="@+id/iv_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal" />
女皇必胜 2024-12-24 15:08:47

如果它不适合你,那么用 android:src 替换 android:background

android:src 将发挥主要作用,

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

它像魅力一样工作正常

在此处输入图像描述

if it's not working for you then replace android:background with android:src

android:src will play the major trick

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

it's working fine like a charm

enter image description here

末蓝 2024-12-24 15:08:47

使用此代码:

<ImageView android:id="@+id/avatar"
           android:layout_width="fill_parent"
           android:layout_height="match_parent"
           android:scaleType="fitXY" />

Use this code:

<ImageView android:id="@+id/avatar"
           android:layout_width="fill_parent"
           android:layout_height="match_parent"
           android:scaleType="fitXY" />
淡淡の花香 2024-12-24 15:08:47

这对我的案例来说是这样的。

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

This did it for my case.

<ImageView android:layout_width="match_parent"
           android:layout_height="wrap_content"     
           android:layout_centerHorizontal="true"         
           android:scaleType="centerCrop"
           android:adjustViewBounds="true" />
殊姿 2024-12-24 15:08:47

我需要一个 ImageView 和一个 Bitmap,因此 Bitmap 会缩放为 ImageView 大小,并且 ImageView 的大小与缩放后的 Bitmap 相同:)。

我正在浏览这篇文章以了解如何做到这一点,最后做了我想要的,但不是这里描述的方式。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/acpt_frag_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/imageBackground"
android:orientation="vertical">

<ImageView
    android:id="@+id/acpt_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:adjustViewBounds="true"
    android:layout_margin="@dimen/document_editor_image_margin"
    android:background="@color/imageBackground"
    android:elevation="@dimen/document_image_elevation" />

然后在 onCreateView 方法中

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_scanner_acpt, null);

    progress = view.findViewById(R.id.progress);

    imageView = view.findViewById(R.id.acpt_image);
    imageView.setImageBitmap( bitmap );

    imageView.getViewTreeObserver().addOnGlobalLayoutListener(()->
        layoutImageView()
    );

    return view;
}

,然后在layoutImageView() 代码中

private void layoutImageView(){

    float[] matrixv = new float[ 9 ];

    imageView.getImageMatrix().getValues(matrixv);

    int w = (int) ( matrixv[Matrix.MSCALE_X] * bitmap.getWidth() );
    int h = (int) ( matrixv[Matrix.MSCALE_Y] * bitmap.getHeight() );

    imageView.setMaxHeight(h);
    imageView.setMaxWidth(w);

}

,结果是图像完美地适合内部,保持宽高比,
当位图位于内部时,ImageView 中不会有额外的剩余像素。

结果

ImageView 拥有这一点很重要
wrap_content 和 adjustmentViewBounds 为 true,
然后setMaxWidth和setMaxHeight就可以了,这是ImageView源码中写的,

/*An optional argument to supply a maximum height for this view. Only valid if
 * {@link #setAdjustViewBounds(boolean)} has been set to true. To set an image to be a
 * maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set
 * adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width
 * layout params to WRAP_CONTENT. */

I needed to have an ImageView and an Bitmap, so the Bitmap is scaled to ImageView size, and size of the ImageView is the same of the scaled Bitmap :).

I was looking through this post for how to do it, and finally did what I want, not the way described here though.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/acpt_frag_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/imageBackground"
android:orientation="vertical">

<ImageView
    android:id="@+id/acpt_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:adjustViewBounds="true"
    android:layout_margin="@dimen/document_editor_image_margin"
    android:background="@color/imageBackground"
    android:elevation="@dimen/document_image_elevation" />

and then in onCreateView method

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_scanner_acpt, null);

    progress = view.findViewById(R.id.progress);

    imageView = view.findViewById(R.id.acpt_image);
    imageView.setImageBitmap( bitmap );

    imageView.getViewTreeObserver().addOnGlobalLayoutListener(()->
        layoutImageView()
    );

    return view;
}

and then layoutImageView() code

private void layoutImageView(){

    float[] matrixv = new float[ 9 ];

    imageView.getImageMatrix().getValues(matrixv);

    int w = (int) ( matrixv[Matrix.MSCALE_X] * bitmap.getWidth() );
    int h = (int) ( matrixv[Matrix.MSCALE_Y] * bitmap.getHeight() );

    imageView.setMaxHeight(h);
    imageView.setMaxWidth(w);

}

And the result is that image fits inside perfectly, keeping aspect ratio,
and doesn't have extra leftover pixels from ImageView when the Bitmap is inside.

Result

It's important ImageView to have
wrap_content and adjustViewBounds to true,
then setMaxWidth and setMaxHeight will work, this is written in the source code of ImageView,

/*An optional argument to supply a maximum height for this view. Only valid if
 * {@link #setAdjustViewBounds(boolean)} has been set to true. To set an image to be a
 * maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set
 * adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width
 * layout params to WRAP_CONTENT. */
一曲琵琶半遮面シ 2024-12-24 15:08:47

我需要在毕加索的约束布局中完成此操作,因此我将上面的一些答案放在一起并提出了这个解决方案(我已经知道我正在加载的图像的长宽比,所以这有帮助):

在 setContentView(...) 之后在我的活动代码中调用

protected void setBoxshotBackgroundImage() {
    ImageView backgroundImageView = (ImageView) findViewById(R.id.background_image_view);

    if(backgroundImageView != null) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int width = displayMetrics.widthPixels;
        int height = (int) Math.round(width * ImageLoader.BOXART_HEIGHT_ASPECT_RATIO);

        // we adjust the height of this element, as the width is already pinned to the parent in xml
        backgroundImageView.getLayoutParams().height = height;

        // implement your Picasso loading code here
    } else {
        // fallback if no element in layout...
    }
}

在我的 XML 中

<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="0dp">

    <ImageView
        android:id="@+id/background_image_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="fitStart"
        app:srcCompat="@color/background"
        android:adjustViewBounds="true"
        tools:layout_editor_absoluteY="0dp"
        android:layout_marginTop="0dp"
        android:layout_marginBottom="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginLeft="0dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <!-- other elements of this layout here... -->

</android.support.constraint.ConstraintLayout>

请注意缺少constraintBottom_toBottomOf 属性。 ImageLoader 是我自己的静态类,用于图像加载 util 方法和常量。

I needed to get this done in a constraint layout with Picasso, so I munged together some of the above answers and came up with this solution (I already know the aspect ratio of the image I'm loading, so that helps):

Called in my activity code somewhere after setContentView(...)

protected void setBoxshotBackgroundImage() {
    ImageView backgroundImageView = (ImageView) findViewById(R.id.background_image_view);

    if(backgroundImageView != null) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int width = displayMetrics.widthPixels;
        int height = (int) Math.round(width * ImageLoader.BOXART_HEIGHT_ASPECT_RATIO);

        // we adjust the height of this element, as the width is already pinned to the parent in xml
        backgroundImageView.getLayoutParams().height = height;

        // implement your Picasso loading code here
    } else {
        // fallback if no element in layout...
    }
}

In my XML

<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="0dp">

    <ImageView
        android:id="@+id/background_image_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="fitStart"
        app:srcCompat="@color/background"
        android:adjustViewBounds="true"
        tools:layout_editor_absoluteY="0dp"
        android:layout_marginTop="0dp"
        android:layout_marginBottom="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginLeft="0dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <!-- other elements of this layout here... -->

</android.support.constraint.ConstraintLayout>

Note the lack of a constraintBottom_toBottomOf attribute. ImageLoader is my own static class for image loading util methods and constants.

寄人书 2024-12-24 15:08:47

我正在使用一个非常简单的解决方案。这是我的代码:

imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.getLayoutParams().height = imageView.getLayoutParams().width;
imageView.setMinimumHeight(imageView.getLayoutParams().width);

我的图片是动态添加到网格视图中的。当你对imageview进行这些设置时,图片可以自动以1:1的比例显示。

I am using a very simple solution. Here my code:

imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.getLayoutParams().height = imageView.getLayoutParams().width;
imageView.setMinimumHeight(imageView.getLayoutParams().width);

My pictures are added dynamically in a gridview. When you make these settings to the imageview, the picture can be automatically displayed in 1:1 ratio.

驱逐舰岛风号 2024-12-24 15:08:47

使用简单的数学来调整图像的大小。您可以调整 ImageView 的大小,也可以调整可绘制图像的大小,而不是 ImageView 上设置的大小。找到您想要在 ImageView 上设置的位图的宽度和高度并调用所需的方法。假设您的宽度 500 大于调用方法的高度

//250 is the width you want after resize bitmap
Bitmat bmp = BitmapScaler.scaleToFitWidth(bitmap, 250) ;
ImageView image = (ImageView) findViewById(R.id.picture);
image.setImageBitmap(bmp);

您使用此类来调整位图大小。

public class BitmapScaler{
// Scale and maintain aspect ratio given a desired width
// BitmapScaler.scaleToFitWidth(bitmap, 100);
 public static Bitmap scaleToFitWidth(Bitmap b, int width)
  {
    float factor = width / (float) b.getWidth();
    return Bitmap.createScaledBitmap(b, width, (int) (b.getHeight() * factor), true);
  }


  // Scale and maintain aspect ratio given a desired height
  // BitmapScaler.scaleToFitHeight(bitmap, 100);
  public static Bitmap scaleToFitHeight(Bitmap b, int height)
  {
    float factor = height / (float) b.getHeight();
    return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, true);
   }
 }

xml 代码是

<ImageView
android:id="@+id/picture"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:adjustViewBounds="true"
android:scaleType="fitcenter" />

Use Simple math to resize the image . either you can resize ImageView or you can resize drawable image than set on ImageView . find the width and height of your bitmap which you want to set on ImageView and call the desired method. suppose your width 500 is greater than height than call method

//250 is the width you want after resize bitmap
Bitmat bmp = BitmapScaler.scaleToFitWidth(bitmap, 250) ;
ImageView image = (ImageView) findViewById(R.id.picture);
image.setImageBitmap(bmp);

You use this class for resize bitmap.

public class BitmapScaler{
// Scale and maintain aspect ratio given a desired width
// BitmapScaler.scaleToFitWidth(bitmap, 100);
 public static Bitmap scaleToFitWidth(Bitmap b, int width)
  {
    float factor = width / (float) b.getWidth();
    return Bitmap.createScaledBitmap(b, width, (int) (b.getHeight() * factor), true);
  }


  // Scale and maintain aspect ratio given a desired height
  // BitmapScaler.scaleToFitHeight(bitmap, 100);
  public static Bitmap scaleToFitHeight(Bitmap b, int height)
  {
    float factor = height / (float) b.getHeight();
    return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, true);
   }
 }

xml code is

<ImageView
android:id="@+id/picture"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:adjustViewBounds="true"
android:scaleType="fitcenter" />
情场扛把子 2024-12-24 15:08:47

快速回答:

<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" />
晚风撩人 2024-12-24 15:08:47

只需将其写在 xml 中

android:scaleType="centerCrop"

对我有用

Just write it in xml

android:scaleType="centerCrop"

Worked for me

请远离我 2024-12-24 15:08:47

就我而言,我发现答案隐藏在这个问题的评论中(归功于@vida)。

android:scaleType="centerInside"

使用android:scaleType="centerInside"而不是android:scaleType="centerCrop"怎么样?它也不会裁剪图像,但确保宽度和高度都小于或等于图像视图的宽度和高度:)这是一个很好的比例类型视觉指南:Android ImageView ScaleType:视觉指南

In my case, I found the answer buried in a comment on this question (credit to @vida).

android:scaleType="centerInside"

How about using android:scaleType="centerInside" instead of android:scaleType="centerCrop"? It would also not crop the image but ensure that both width and height are less than or equal the imageview's width and height :) Here's a good visual guide for scaletypes: Android ImageView ScaleType: A Visual Guide

濫情▎り 2024-12-24 15:08:47

Jarno Argillander 的答案的 kotlin 版本用于我的应用程序

    /**
 * scale the image represented in the bitmap.
 * Refer to [stackoverflow](https://stackoverflow.com/questions/8232608/fit-image-into-imageview-keep-aspect-ratio-and-then-resize-imageview-to-image-d)
 * answer of [Jarno Argillander](https://stackoverflow.com/users/1030049/jarno-argillander)
 *
 * @param bitmap bitmap of the image
 * @param view imageview where the image will be displayed
 * @see .dpToPx
 */
@Throws(NoSuchElementException::class)
private fun scaleImage(bitmap: Bitmap?, view: ImageView) {
    // Get current dimensions AND the desired bounding box
    var width: Int
    width = try {
        bitmap!!.width
    } catch (e: NullPointerException) {
        throw NoSuchElementException("Can't find bitmap on given view/drawable")
    }
    var height = bitmap.height
    val bounding = dpToPx(150)
    // Determine how much to scale: the dimension requiring less scaling is
    // closer to the its side. This way the image always stays inside your
    // bounding box AND either x/y axis touches it.
    val xScale = bounding.toFloat() / width
    val yScale = bounding.toFloat() / height
    val scale = if (xScale <= yScale) xScale else yScale
    // Create a matrix for the scaling and add the scaling data
    val matrix = Matrix()
    matrix.postScale(scale, scale)
    // Create a new bitmap and convert it to a format understood by the ImageView
    val scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true)
    width = scaledBitmap.width // re-use
    height = scaledBitmap.height // re-use
    val result = BitmapDrawable(context.resources, scaledBitmap)
    // Apply the scaled bitmap
    view.setImageDrawable(result)
    // Now change ImageView's dimensions to match the scaled image
    val params = view.layoutParams as ConstraintLayout.LayoutParams
    params.width = width
    params.height = height
    view.layoutParams = params
}

/**
 * calculate the dimensions of desired bounding box.
 *
 *
 * @param dp int with dimensions of desired bounding box
 * @return int with dimensions of desired bounding box in px
 */
private fun dpToPx(dp: Int): Int {
    val density = applicationContext.resources.displayMetrics.density
    return Math.round(dp.toFloat() * density)
}

kotlin version of Jarno Argillander's answer used for my app

    /**
 * scale the image represented in the bitmap.
 * Refer to [stackoverflow](https://stackoverflow.com/questions/8232608/fit-image-into-imageview-keep-aspect-ratio-and-then-resize-imageview-to-image-d)
 * answer of [Jarno Argillander](https://stackoverflow.com/users/1030049/jarno-argillander)
 *
 * @param bitmap bitmap of the image
 * @param view imageview where the image will be displayed
 * @see .dpToPx
 */
@Throws(NoSuchElementException::class)
private fun scaleImage(bitmap: Bitmap?, view: ImageView) {
    // Get current dimensions AND the desired bounding box
    var width: Int
    width = try {
        bitmap!!.width
    } catch (e: NullPointerException) {
        throw NoSuchElementException("Can't find bitmap on given view/drawable")
    }
    var height = bitmap.height
    val bounding = dpToPx(150)
    // Determine how much to scale: the dimension requiring less scaling is
    // closer to the its side. This way the image always stays inside your
    // bounding box AND either x/y axis touches it.
    val xScale = bounding.toFloat() / width
    val yScale = bounding.toFloat() / height
    val scale = if (xScale <= yScale) xScale else yScale
    // Create a matrix for the scaling and add the scaling data
    val matrix = Matrix()
    matrix.postScale(scale, scale)
    // Create a new bitmap and convert it to a format understood by the ImageView
    val scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true)
    width = scaledBitmap.width // re-use
    height = scaledBitmap.height // re-use
    val result = BitmapDrawable(context.resources, scaledBitmap)
    // Apply the scaled bitmap
    view.setImageDrawable(result)
    // Now change ImageView's dimensions to match the scaled image
    val params = view.layoutParams as ConstraintLayout.LayoutParams
    params.width = width
    params.height = height
    view.layoutParams = params
}

/**
 * calculate the dimensions of desired bounding box.
 *
 *
 * @param dp int with dimensions of desired bounding box
 * @return int with dimensions of desired bounding box in px
 */
private fun dpToPx(dp: Int): Int {
    val density = applicationContext.resources.displayMetrics.density
    return Math.round(dp.toFloat() * density)
}
恰似旧人归 2024-12-24 15:08:47

我只是在 ConstraintLayout 中使用 ImageView 并将 ImageView 中的 adjustmentviewbound 设置为 true 。

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:src="@drawable/myimg"
        android:adjustViewBounds="true"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

I just use ImageView inside ConstraintLayout and set adjustviewbound in ImageView to true.

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:src="@drawable/myimg"
        android:adjustViewBounds="true"
        />

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