问题示例
activity_main.xml中有一个Button和ImageView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/gitPic"
android:text="加载图片"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/showPic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
MainActivity通过Button加载图片
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button gitPicBtn = findViewById(R.id.gitPic);
ImageView showPic = findViewById(R.id.showPic);
gitPicBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showPic.setImageResource(R.drawable.test);
}
});
}
}
测试图片为14.2M(可用Ps增加分辨率生成大图),点击加载按钮后报错
解决办法
- 使用BitmapFactory.decodeResource()解析图片
- BitmapFactory.Options的公有属性inSampleSize为图片设置缩放比例,等于2则为1/2
- BitmapFactory.Options的公有属性inJustDecodeBounds为true表示不将图片加载到内存(就不会报错)
- 先根据控件大小和图片大小计算图片缩放比再加载图片
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button gitPicBtn = findViewById(R.id.gitPic);
gitPicBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadBigImage();
}
});
}
public void loadBigImage() {
ImageView imageView = this.findViewById(R.id.showPic);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.drawable.test, options);
int width = options.outWidth;
int height = options.outHeight;
int measuredWidth = imageView.getMeasuredWidth();
int measuredHeight = imageView.getMeasuredHeight();
int sampleSize;
if (width < measuredWidth || height < measuredHeight) {
sampleSize = 1;
} else {
int scaleX = width / measuredWidth;
int scaleY = height / measuredHeight;
sampleSize = Math.max(scaleX, scaleY);
}
options.inSampleSize = sampleSize;
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test, options);
imageView.setImageBitmap(bitmap);
}
}
|