本文共 2952 字,大约阅读时间需要 9 分钟。
-
- public static int getBytesPerPixel(Bitmap.Config config) {
- if (config == Bitmap.Config.ARGB_8888) {
- return 4;
- } else if (config == Bitmap.Config.RGB_565) {
- return 2;
- } else if (config == Bitmap.Config.ARGB_4444) {
- return 2;
- } else if (config == Bitmap.Config.ALPHA_8) {
- return 1;
- }
- return 1;
- }
-
- public static long getBitmapSizeInMemory(int imageW, int imageH) {
- return imageH * imageW * getBytesPerPixel(Bitmap.Config.ARGB_8888);
- }
-
- public static int getScaleInSampleSize(int resW, int resH, int desW, int desH) {
- int scaleW = resW / desW;
- int scaleH = resH / desH;
- int largeScale = scaleH > scaleW ? scaleH : scaleW;
- int sampleSize = 1;
- while (sampleSize < largeScale) {
- sampleSize *= 2;
- }
- return sampleSize;
- }
-
- public static Bitmap decodeBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight)
- {
-
- final BitmapFactory.Options options = new BitmapFactory.Options();
- options.inJustDecodeBounds = true;
- BitmapFactory.decodeResource(res, resId, options);
- int height = options.outHeight;
- int width = options.outWidth;
- String mimeType = options.outMimeType;
-
- options.inSampleSize = getScaleInSampleSize(width, height, reqWidth, reqHeight);
-
-
- options.inJustDecodeBounds = false;
- return BitmapFactory.decodeResource(res, resId, options);
- }
- private LruCache<String, Bitmap> mMemoryCache;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
-
-
- int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
-
- int cacheSize = maxMemory / 6;
- mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
- @Override
- protected int sizeOf(String key, Bitmap bitmap) {
-
- return bitmap.getByteCount() / 1024;
- }
- };
- }
- public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
- if (getBitmapFromMemCache(key) == null) {
- mMemoryCache.put(key, bitmap);
- }
- }
- public Bitmap getBitmapFromMemCache(String key) {
- return mMemoryCache.get(key);
- }
- public void loadBitmap(int resId, ImageView imageView) {
- final String imageKey = String.valueOf(resId);
- final Bitmap bitmap = getBitmapFromMemCache(imageKey);
- if (bitmap != null) {
- imageView.setImageBitmap(bitmap);
- } else {
-
- imageView.setImageResource(R.drawable.image_default);
- LoadWorkerTask task = new LoadWorkerTask();
- task.execute(resId);
- }
- }
- class LoadWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
-
- @Override
- protected Bitmap doInBackground(Integer... params) {
- final Bitmap bitmap = decodeBitmapFromResource(
- getResources(), params[0], 100, 100);
- addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
- return bitmap;
- }
- }
转载地址:http://qbfpn.baihongyu.com/