Android编程实现等比例显示图片的方法

2019-12-10 19:53:03于海丽

建议使用如下的这种,应用了LruCache作为管理

 

 
  1. public class ImageUtil {  private LruCache<String, Bitmap> mMemoryCache; 
  2. private final Context mContext;  private static ImageUtil imageUtil; 
  3. private static Object obj = new Object();  private int memClass; 
  4. private int cacheSize;  private ImageUtil(Context mContext) { 
  5. this.mContext = mContext;  createLruCache(mContext); 
  6. }  private void createLruCache(Context mContext) { 
  7. memClass = ((ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();  cacheSize = 1024 * 1024 * memClass / 8; 
  8. mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {  @Override 
  9. protected int sizeOf(String key, Bitmap value) {  // TODO Auto-generated method stub 
  10. return value.getRowBytes();  } 
  11. };  } 
  12. public static ImageUtil getInstance(Context mContext) {  if (imageUtil == null) { 
  13. synchronized (obj) {  if (imageUtil == null) { 
  14. imageUtil = new ImageUtil(mContext);  } 
  15. }  } 
  16. return imageUtil;  } 
  17. public void adjustImageSize(ImageView imageView, int imageResourceId) {  Bitmap mBitmap = null; 
  18. Display display = ((MainActivity) mContext).getWindowManager().getDefaultDisplay();  int width = display.getWidth(); // deprecated 
  19. int height = display.getHeight(); // deprecated  Bitmap bitmapCache = mMemoryCache.get(imageResourceId + ""); 
  20. if (bitmapCache != null) {  mBitmap = bitmapCache; 
  21. } else {  mBitmap = createImageWithResouce(mContext, imageResourceId); 
  22. mMemoryCache.put(imageResourceId + "", mBitmap);  } 
  23. RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width, width  / getBitmapWidth(mBitmap) * getBitmapHeight(mBitmap));