.Android在加载大背景图或者大图片时,经常导致内存溢出(Out of Memory Error)
可们可能跟据imageView的宽高来对图片进行压缩,关效的解决(Out of Memory Error)
直接上代码 :
xml
<RelativeLayout 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: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=".MainActivity" >
<ImageView
android:src="@drawable/ic_launcher"
android:id="@+id/image"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
/>
<Button
android:onClick="onClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
java
ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image=(ImageView) findViewById(R.id.image);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View view){
//解析图片时需要使用到的参数都封装在这个对象里了
Options opt = new Options();
//不为像素申请内存,只获取图片宽高
opt.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.drawable.dog, opt);
//拿到图片宽高
int imageWidth = opt.outWidth;
int imageHeight = opt.outHeight;
Display dp = getWindowManager().getDefaultDisplay();
//拿到屏幕宽高
int screenWidth = dp.getWidth();
int screenHeight = dp.getHeight();
//计算缩放比例
int scale = 1;
int scaleWidth = imageWidth / screenWidth;
int scaleHeight = imageHeight / screenHeight;
int max=Math.max(scaleWidth, scaleHeight);
if (max>scale) {
scale=max;
}
//设置缩放比例
opt.inSampleSize = scale;
opt.inJustDecodeBounds = false;
Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.dog, opt);
image.setImageBitmap(bitmap);
}
}