Mat*_*att 17 android scale android-imageview
的src应拉伸其宽度match_parent,同时保持高宽比.当图像大于父图像时,它会正确缩小.但是当图像较小时,它不会向上扩展.(插图显示了所需的行为).

<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伸展width唯一
And*_*Res 23
我认为这是不可能的,至少不是scaleType属性提供的选项.
在这种情况下,您最好的选择是使用centerCrop,但只能看到图片的中心.
但是,如果您对此选项不满意,则可以以编程方式缩放图像而不会丢失纵横比.为了实现这一点,您需要根据屏幕宽度计算比例因子,然后使用此比例因子来了解图像的新高度.
像这样:
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" />
setContentView(R.layout.activity_main);
ImageView imageView = (ImageView)findViewById(R.id.imageView);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
int imageWidth = bitmap.getWidth();
int imageHeight = bitmap.getHeight();
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
int newWidth = metrics.widthPixels;
float scaleFactor = (float)newWidth/(float)imageWidth;
int newHeight = (int)(imageHeight * scaleFactor);
bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
imageView.setImageBitmap(bitmap);
布局
<ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scaleType="centerInside"
    android:src="@drawable/image" />
小智 5
用这个 MainImage.setScaleType(ImageView.ScaleType.FIT_XY);
或者,您可以简单地添加android:scaleType="fitXY"xml。
| 归档时间: | 
 | 
| 查看次数: | 19892 次 | 
| 最近记录: |