拉伸图像以适合 [英] Stretch Image to Fit

查看:193
本文介绍了拉伸图像以适合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的src 应延伸其宽度 match_parent ,同时保持高宽比。当图像是比母体大,它正确地按比例缩小。但是,当该图像是较小的,它不会扩大。 (图显示期望的行为)。

The src should stretch its width to match_parent, while keeping aspect ratio. When the image is larger than the parent, it scales down correctly. But when the image is smaller, it does not scale up. (illustration shows desired behavior).

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/banner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter"
        android:adjustViewBounds="true"
        android:src="@drawable/foo"
        />

</RelativeLayout>



使用 ScaleType.fitXY 拉伸宽度

推荐答案

我认为是不可能的,至少不会与 scaleType 属性提供的选项。
在这种情况下,最好的选择是使用 centerCrop ,但画面只有中心将是可见的。

I believe that is not possible, at least not with the options provided by scaleType attribute.
Your best option in this case is to use centerCrop, but only the center of the picture will be visible.

不过,如果你是不是确定与该选项,那么你可以以编程方式缩放图像不会丢失宽高比。 为了做到这一点,你需要计算一个比例系数根据屏幕的宽度,然后用这个比例系数知道图像的新高度。

However, if you are not ok with this option, then you could scale the image programatically without loosing aspect ratio. In order to achieve this you'll need to calculate a scale factor based on the screen width, and then use this scale factor to know the new height of the image.

这样的:

ImageView imageView = (ImageView)findViewById(R.id.imageView);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.foo);

int imageWidth = bitmap.getWidth();
int imageHeight = bitmap.getHeight();

int newWidth = getScreenWidth(); //this method should return the width of device screen.
float scaleFactor = (float)newWidth/(float)imageWidth;
int newHeight = (int)(imageHeight * scaleFactor);

bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
imageView.setImageBitmap(bitmap);

此外,你需要调整的ImageView 的声明布局文件:

<ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

这篇关于拉伸图像以适合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆