package com.jianda.zuci.showbigphoto;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private ImageView iv_bigPhoto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv_bigPhoto = (ImageView)findViewById(R.id.iv_bigPhoto);
int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);//得到系统内存大小
Log.v("maxMemory",maxMemory+"KB");
iv_bigPhoto.setImageBitmap(decodeSampledBitmapFromResource(getResources(),R.drawable.bigphoto,256,144));
}
public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight){
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;//If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory.
if (height > reqHeight || width > reqWidth){
final int heightRatio = Math.round((float)height / (float)reqHeight);
final int widthRatio = Math.round((float)width / (float)reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
Log.v("inSampleSize",Integer.toString(inSampleSize));
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;//属性设置为true就可以让解析方法禁止为bitmap分配内存,返回值也不再是一个Bitmap对象,而是null
BitmapFactory.decodeResource(res,resId,options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,reqHeight);
Log.v("压缩比",Integer.toString(options.inSampleSize));
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
}
运行效果: