Android根据屏幕宽度缩放图片

来源:互联网 发布:c语言输出*等腰三角形 编辑:程序博客网 时间:2024/05/16 19:55

对于图像的显示处理,之前关注过一篇文章:ImageView.ScaleType设置图解
http://blog.csdn.net/larryl2003/article/details/6919513,主要是通过android:scaleType来定义,
1. SetScaleType(ImageView.ScaleType.CENTER);按图片的原来size居中显示,当图片长/宽超过View的长/宽,则截取图片的居中部分显示
2. SetScaleType(ImageView.ScaleType.CENTER_CROP);按比例扩大图片的size居中显示,使得图片长(宽)等于或大于View的长(宽)
3. setScaleType(ImageView.ScaleType.CENTER_INSIDE);将图片的内容完整居中显示,通过按比例缩小或原来的size使得图片长/宽等于或小于View的长/宽
4. setScaleType(ImageView.ScaleType.FIT_CENTER);把图片按比例扩大/缩小到View的宽度,居中显示
5. FIT_XY;不按比例缩放图片,目标是把图片塞满整个View。

但是,如果要让图片宽度填满屏幕宽度,而图片又不拉升变形,也就是让其适应屏幕宽度,而图片高度则相应的缩放。

 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.about_us);        int bwidth = bitmap.getWidth();        int bHeight = bitmap.getHeight();        DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();        int width = displayMetrics.widthPixels;        int height = width * bHeight / bwidth;        ViewGroup.LayoutParams para = about_us.getLayoutParams();//        final float scale = getResources().getDisplayMetrics().density;        para.height = height;        about_us.setLayoutParams(para);

而对应的布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <android.support.v7.widget.Toolbar        android:id="@+id/toolbar"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:background="?attr/colorPrimary"        android:minHeight="?attr/actionBarSize" /><!--如果图片高度太高,超过屏幕高度的话建议使用scrollView-->    <ScrollView        android:id="@+id/scrollView"        android:layout_width="match_parent"        android:layout_height="wrap_content">        <ImageView            android:id="@+id/about_us"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:src="@mipmap/about_us"            />    </ScrollView></LinearLayout>
0 0