加载大图
布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.a510.MainActivity">
<Button
android:layout_centerHorizontal="true"
android:id="@+id/btn_show"
android:text="加载大图"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:layout_below="@id/btn_show"
android:id="@+id/iv_show"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
初始化控件
//初始化控件
iv_show = (ImageView) findViewById(R.id.iv_show)
btn_show = (Button) findViewById(R.id.btn_show)
将Mainactivity实现接口,并实现里面的onclick方法
public class MainActivity extends AppCompatActivity implements View.OnClickListener
//给按钮设置点击事件
btn_show.setOnClickListener(this);
public void onClick(View v) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(path,options);
int outWidth = options.outWidth;
int outHeight = options.outHeight;
if (outHeight>height||outWidth>width){
int xIndex = outWidth/width;
int yIndex = outHeight/height;
int max = Math.max(xIndex, yIndex);
options.inSampleSize = max;
Log.e("MainActivity",max+"");
}
计算好压缩的比例之后,对 inJustDecodeBounds设置为false后才能对图片进行解码
options.inJustDecodeBounds = false
bitmap = BitmapFactory.decodeFile(path,options)
//将图片设置在ImageView中
iv_show.setImageBitmap(bitmap)