Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/185.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 将随机大小的图像适配到ImageView中_Android_Imageview - Fatal编程技术网

Android 将随机大小的图像适配到ImageView中

Android 将随机大小的图像适配到ImageView中,android,imageview,Android,Imageview,我有一个imageview,稍后它将包含一些随机大小的图像 我想用图像填充imageview,但是 保持比例(因此不要使用缩放类型FITXY或centercrop,因为它会修剪图像的一部分) 我该怎么做 在这个测试代码中,我在图像的左右两侧都有空格 <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android

我有一个imageview,稍后它将包含一些随机大小的图像 我想用图像填充imageview,但是 保持比例(因此不要使用缩放类型FITXY或centercrop,因为它会修剪图像的一部分)

我该怎么做

在这个测试代码中,我在图像的左右两侧都有空格

    <?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="fill_parent"


     >

   <ImageView
        android:id="@+id/imgTest"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter"

        android:src="@drawable/test"
      />


通过矩阵和我的屏幕的高度/宽度进行解析

private Bitmap resize(Bitmap bm, int w, int h)
    {
        int width = bm.getWidth();
        int height = bm.getHeight();
        int newWidth = w;
        int newHeight = h;
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);

        return resizedBitmap;
    }
试试这个:

<ImageView
    android:id="@+id/imgTest"
    android:layout_width="wrap_content"
    android:layout_height="100dp"
    android:layout_alignParentLeft="true"
    android:paddingRight="20dp"
    android:scaleType="fitStart"
    android:src="@drawable/test"/>