如果一个图片很大的话加载到屏幕中就可能造成内存溢出,为了解决这个问题,我们把一个很大的图片进行等比缩放至最适合屏幕的图片。
怎么来进行缩放呢?
图片的/屏幕宽=比例1;
图片高/屏幕高=比例2;
然后来看哪个比例大用哪个
package com.example.image; import android.os.Bundle; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.view.Display; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.widget.ImageView; public class MainActivity extends Activity { private ImageView img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); img = (ImageView) findViewById(R.id.img); findViewById(R.id.btn).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Options options = new Options(); //请求图片但不申请内存 options.inJustDecodeBounds = true; BitmapFactory.decodeFile("sdcard/dog.jpg",options); //获取图片宽高 int imgWidth = options.outWidth; int imgHeight = options.outHeight; //获得屏幕宽高 Display dis = getWindowManager().getDefaultDisplay(); int w = dis.getWidth(); int h = dis.getHeight(); //算出图片和屏幕缩放的比例 int widthB = imgWidth/w; int heightB = imgHeight/h; int result = 1; //取大的倍数 if(widthB>=heightB && widthB>1){ result = widthB; }else if(widthB<heightB && heightB>1){ result = heightB; } //设置缩放比例 options.inSampleSize=result; //请求内存 options.inJustDecodeBounds = false; Bitmap bitmap = BitmapFactory.decodeFile("sdcard/dog.jpg",options); img.setImageBitmap(bitmap); } }); } }