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

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

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


当前回答

传递你的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);
    }

其他回答

如果你想要一个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);

我花了一段时间才让它工作,但这似乎在图像小于屏幕宽度和大于屏幕宽度的情况下都可以工作,而且它不会将图像框起来。

我用这个:

<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" />

使用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"

上面的例子对我很有用。

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

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

键在width和height的匹配父项中

imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 130, 110, false));