android Caching Bitmaps學習,androidbitmaps

來源:互聯網
上載者:User

android Caching Bitmaps學習,androidbitmaps

參考連結:

Displaying Bitmaps Efficiently

Caching Bitmaps 翻譯

先吐槽一下:google 給樣本中都有錯誤的地方,國內翻譯的也不去掉錯誤.太坑.

Google官方Download the sample

 也可參照guolin的文章, 


經過一番學習,初步實踐完成.貼出來,備用.

package com.akm.testlrucache;import android.app.Activity;import android.content.Context;import android.content.res.Resources;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.AsyncTask;import android.support.v4.util.LruCache;import android.util.DisplayMetrics;import android.view.Window;import android.view.WindowManager;import android.widget.ImageView;public class BitmapCacheUtil {private Context context;private int screenWidth = 0; private int screenHeight = 0;private final int TITLE_HEIGHT = 48;private ImageView imageView;private int resid;private LruCache<String, Bitmap> mMemoryCache;  private BitmapWorkerTask  task ;  public BitmapCacheUtil(Context context , ImageView imageView,int resid) {this.context = context;this.imageView = imageView;this.resid =resid; int maxMemory = (int) Runtime.getRuntime().maxMemory();  int cacheSize = maxMemory / 8;  mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {  @Override  protected int sizeOf(String key, Bitmap bitmap) {  return bitmap.getByteCount();  }  };  loadBitmap();}public void loadBitmap() {   Bitmap bitmap = getBitmapFromMemoryCache(String.valueOf(resid));if (bitmap==null) {// mImageView.setImageResource(R.drawable.image_placeholder);task = new BitmapWorkerTask();  task.execute(resid); }else{imageView.setImageBitmap(bitmap);  } }  private Bitmap getBitmapFromMemoryCache(String key) {  return mMemoryCache.get(key);  }  private void addBitmapToMemoryCache(String key, Bitmap bitmap) {  if (getBitmapFromMemoryCache(key) == null) {  mMemoryCache.put(key, bitmap);  }  }  protected void setImageView() {  Bitmap bitmap = getBitmapFromMemoryCache(String.valueOf(resid));  if (bitmap != null) {  imageView.setImageBitmap(bitmap);  } else {  imageView.setImageResource(R.drawable.ic_launcher);  }  }  class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {   @Override  protected Bitmap doInBackground(Integer... params) {  final Bitmap bitmap = decodeSampledBitmapFromResource(context.getResources(), params[0], getScreenWidth(context), getScreenHeight(context));addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);return bitmap;}  @Override  protected void onPostExecute(Bitmap bitmap) {  super.onPostExecute(bitmap);  if (bitmap != null) {  imageView.setImageBitmap(bitmap);   }  }   }  public Bitmap decodeSampledBitmapFromResource(Resources res, int resId,int reqWidth, int reqHeight) {// First decode with inJustDecodeBounds=true to check dimensionsfinal BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true;BitmapFactory.decodeResource(res, resId, options);// Calculate inSampleSizeoptions.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);// Decode bitmap with inSampleSize setoptions.inJustDecodeBounds = false;return BitmapFactory.decodeResource(res, resId, options);}public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {// Raw height and width of imagefinal int height = options.outHeight;final int width = options.outWidth;int inSampleSize = 1;if (height > reqHeight || width > reqWidth) {if (width > height) {inSampleSize = Math.round((float)height / (float)reqHeight);} else {inSampleSize = Math.round((float)width / (float)reqWidth);}}return inSampleSize;}public void cancelTask() {  if (task != null) {  task.cancel(false);  }  }  @SuppressWarnings("deprecation")public int getScreenWidth(Context context) {if (screenWidth != 0) {return screenWidth;}WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);screenWidth = wm.getDefaultDisplay().getWidth();return screenWidth;}@SuppressWarnings("deprecation")public int getScreenHeight(Context context) {if (screenHeight != 0) {return screenHeight;}int top = 0;if (context instanceof Activity) {top = ((Activity) context).getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();if (top == 0) {top = (int) (TITLE_HEIGHT * getScreenDensity(context));}}WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);screenHeight = wm.getDefaultDisplay().getHeight() - top;return screenHeight;}public float getScreenDensity(Context context) {WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);DisplayMetrics metric = new DisplayMetrics();wm.getDefaultDisplay().getMetrics(metric);return metric.density;}public float getScreenDensityDpi(Context context) {WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);DisplayMetrics metric = new DisplayMetrics();wm.getDefaultDisplay().getMetrics(metric);return metric.densityDpi;}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.