Imageview 加载网络图片 图片动态处理 图片不变形的方法

一、图片不变形的方法(条件,该ImageView没有设置margin和padding的情况下,要不还是会变形):

1.  imv.setScaleType(ScaleType.FIX_XY); 

2. ImageView 的宽高设置为:宽匹配父类,高度包裹内容(根据需求,可以适当地改换下也行)

二、图片不变形的方法(条件,设置了margin或者padding):

int i=0;
				if (!StringUtil.isEmpty(fdProdSummary) && matcherSummary.groupCount() != 0) {
					
					while(matcherSummary.find()) {
						
						OOMImageView imv = new OOMImageView(context);
						imv.setScaleType(ScaleType.FIT_XY); 
						DisplayMetrics dm = new DisplayMetrics();
						((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(dm);
						int W = dm.widthPixels;
						int H = 0;
						Integer w_h[] = BitmapManage.getInstance(context).get( matcherSummary.group(), imv);
						LinearLayout.LayoutParams llp;
						if (w_h!=null) {
							H = (int) ((w_h[1]*1.0)/(w_h[0]*1.0)*W)	- 50;
							if (H == 0)
								llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
							else 
								llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,H);
						} else {
							llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
						}
						llp.setMargins(25, 0, 25, 10);
						imv.setLayoutParams(llp);
						
						productImgsContainer.addView(imv);
						// W*H 947/473
						/*<ImageView
	                    android:layout_width="match_parent"
	                    android:layout_height="150dp"
	                    android:layout_marginBottom="70dp"
	                    android:layout_marginLeft="25dp"
	                    android:layout_marginRight="25dp"
	                    android:scaleType="fitXY"
	                    android:src="@drawable/logo_pgg_p" />*/
					}
				} 



Imageview 加载网络图片 图片动态处理 方法如下:


int i=0;
				if (!StringUtil.isEmpty(fdProdSummary) && matcherSummary.groupCount() != 0) {
					
					fdProdSummarys = new String[matcherSummary.groupCount()];
					matcherSummary.find();
					for(;i<matcherSummary.groupCount();i++) {
						fdProdSummarys[i] = matcherSummary.group();
						OOMImageView imv = new OOMImageView(context);
						imv.setScaleType(ScaleType.FIT_CENTER); 
						DisplayMetrics dm = new DisplayMetrics();
						((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(dm);
						int W = dm.widthPixels;
						int H = (int) (473.0 / 947.0*W);
						LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
						llp.setMargins(25, 0, 25, 70);
						imv.setLayoutParams(llp);
						BitmapManage.getInstance(context).get(fdProdSummarys[i], imv);
						productImgsContainer.addView(imv);
						// W*H 947/473
						/*<ImageView
	                    android:layout_width="match_parent"
	                    android:layout_height="150dp"
	                    android:layout_marginBottom="70dp"
	                    android:layout_marginLeft="25dp"
	                    android:layout_marginRight="25dp"
	                    android:scaleType="fitXY"
	                    android:src="@drawable/logo_pgg_p" />*/
					}
				} 



附上Bitmap图片处理:

package com.lvche.frame.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.view.Display;
import android.view.View;
import android.widget.ImageView;

import com.lvche.frame.httpUtils.HttpManage;

/**
 * 图片管理类(单例类)
 * @author William
 *
 */
public class BitmapManage {
	private final String TAG = "BitmapManage";
	
	public static BitmapManage bitmapManage = null;
	public Context context = null;
	public static final int MAX_CACHE = 30;
	public static final int REMOVE_CACHE = MAX_CACHE / 5;
	private HashMap<String, Bitmap> bitmapMap = null;
	private static String imageCachePath = null;
	private List<String> bitmapKeyList = null;
	
	private int loadCount = 0;
	private List<WillLoadModel> willLoadList = null;
	public static boolean isRemoveLast = false;
	
	private BitmapManage() {}
	
	private BitmapManage(Context context) {
		this.context = context;
		bitmapMap = new HashMap<String, Bitmap>();
		bitmapKeyList = new ArrayList<String>();
		willLoadList = new ArrayList<WillLoadModel>();
		
		//创建缓存图片目录
		FileUtil.createAppImageFile(context);
		//获取缓存图片目录地址
		imageCachePath = FileUtil.getAppImageFilePath(context);
	}
	
	/**
	 * 获取类对象
	 * @param context
	 * @return
	 */
	public static BitmapManage getInstance(Context context) {
		if (bitmapManage == null) {
			bitmapManage = new BitmapManage(context);
		}
		
		return bitmapManage;
	}
	
	/**
	 * 获取图片,先到缓存内取,否则再到缓存目录取,最后从网络上下载
	 * @param url 图片网络地址
	 * @param imageView 要显示图的imageView
	 * @return
	 */
	public Integer[] get(String url, ImageView imageView) {
		String key = MD5.getMD5(url);
		Bitmap bitmap = bitmapMap.get(key + "0");
		if (bitmap == null) {
			String suffix = url.substring(url.length() - 4, url.length()).replace("/", "-");
			String pathName = imageCachePath + key + suffix;
			bitmap = decodeBitmap(pathName);
			if (bitmap == null) {
				if (loadCount < 3) {
					new LoadHpptBitmapTask(url, imageView, false, true).execute("");
				} else {
					willLoadList.add(new WillLoadModel(url, imageView, false, true));
				}
				return null;
			}
			put(key + "0", bitmap);
		}
		
		imageView.setImageBitmap(bitmap);
		
		return new Integer[] {
				bitmap.getWidth(),
				bitmap.getHeight()
		};
//		ViewGroup.LayoutParams params = imageView.getLayoutParams();
//		params.height = bitmap.getHeight() * params.width / bitmap.getHeight() ;
//		imageView.setLayoutParams(params);
//		return bitmap;
	}
	
	/**
	 * 获取图片,先到缓存内取,否则再到缓存目录取,最后从网络上下载
	 * @param url 图片网络地址
	 * @param imageView 要显示图的imageView
	 * @return
	 */
	public void get(String url, View view, boolean isCache) {
		if (! isCache) {
			new LoadHpptBitmapTask(url, view, false, isCache).execute("");
			return;
		}
		
		String key = MD5.getMD5(url);
		Bitmap bitmap = bitmapMap.get(key + "0");
		if (bitmap == null) {
			String suffix = url.substring(url.length() - 4, url.length()).replace("/", "-");
			String pathName = imageCachePath + key + suffix;
			bitmap = decodeBitmap(pathName);
			if (bitmap == null) {
				if (loadCount < 3) {
					new LoadHpptBitmapTask(url, view, false, isCache).execute("");
				} else {
					willLoadList.add(new WillLoadModel(url, view, false, isCache));
				}
				return;
			}
			put(key + "0", bitmap);
		}
		
		if (view instanceof ImageView) {
			((ImageView) view).setImageBitmap(bitmap);
		} else {
			view.setBackgroundDrawable(new BitmapDrawable(bitmap));
		}
//		ViewGroup.LayoutParams params = imageView.getLayoutParams();
//		params.height = bitmap.getHeight() * params.width / bitmap.getHeight() ;
//		imageView.setLayoutParams(params);
//		return bitmap;
	}
	
	public void getScale(String url, View view, boolean isCache) {
		if (! isCache) {
			new LoadHpptBitmapTask(url, view, false, isCache).execute("");
			return;
		}
		
		String key = MD5.getMD5(url);
		Bitmap bitmap = bitmapMap.get(key + "1");
		if (bitmap == null) {
			String suffix = url.substring(url.length() - 4, url.length());
			String pathName = imageCachePath + key + suffix;
			
			Options opts = new Options();
			opts.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(pathName, opts);
			opts.inSampleSize = computeInitialSampleSize(opts, -1, 256 * 256);
			opts.inJustDecodeBounds = false;
			bitmap = BitmapFactory.decodeFile(pathName, opts);
			if (bitmap == null) {
				if (loadCount < 3) {
					new LoadHpptBitmapTask(url, view, true, isCache).execute("");
				} else {
					willLoadList.add(new WillLoadModel(url, view, true, isCache));
				}
				return;
			}
			put(key + "1", bitmap);
		}
		
		if (view instanceof ImageView) {
			((ImageView) view).setImageBitmap(bitmap);
		} else {
			view.setBackgroundDrawable(new BitmapDrawable(bitmap));
		}
//		ViewGroup.LayoutParams params = imageView.getLayoutParams();
//		params.height = bitmap.getHeight() * params.width / bitmap.getHeight() ;
//		imageView.setLayoutParams(params);
//		return bitmap;
	}
	
	/**
	 * 图片加入到缓存内
	 * @param key
	 * @param bitmap
	 */
	public void put(String key, Bitmap bitmap) {
		//暂时屏蔽回收机制
		//recycle();
		
		bitmapMap.put(key, bitmap);
		if (isRemoveLast) {
			bitmapKeyList.add(0, key);
		} else {
			bitmapKeyList.add(key);
		}
	}
	
	/**
	 * 缓存内图片个数
	 * @return
	 */
	public int getCount() {
		return bitmapMap.size();
	}
	
	/**
	 * 回收图片,释放内存
	 */
	private void recycle() {
		if (bitmapMap.size() == MAX_CACHE) {
			Bitmap bitmap = null;
//			int removeCount = 0;
//			Iterator<String> iterator = bitmapMap.keySet().iterator();
//			while (iterator.hasNext()) {
//				String keyBp = iterator.next();
//				bitmap = bitmapMap.get(keyBp);
//				iterator.remove();
//				bitmapMap.remove(keyBp);
//				if (bitmap != null && !bitmap.isRecycled()) {
//					bitmap.recycle();
//					bitmap = null;
//					LogUtil.i(TAG, "释放图片:" + keyBp);
//				}
//				removeCount++;
//				if (removeCount == REMOVE_CACHE) {
//					break;
//				}
//			}
			int removeIndex = 0;
			
			for (int i = 0; i < REMOVE_CACHE; i++) {
				if(isRemoveLast)
					removeIndex = bitmapKeyList.size() - 1;
				else
					removeIndex = 0;
				String keyBp = bitmapKeyList.get(removeIndex);
				bitmap = bitmapMap.get(keyBp);
				bitmapKeyList.remove(removeIndex);
				bitmapMap.remove(keyBp);
				if (bitmap != null && !bitmap.isRecycled()) {
					bitmap.recycle();
					bitmap = null;
					LogUtil.i(TAG, "释放图片:" + keyBp);
				}
			}
			System.gc();
		}
	}
	
	/**
	 * 删除scard下一月以前的缓存图片
	 */
	public static void delBitampFormSDCard() {
		File[] bitmapFiles = FileUtil.getDirChildFile(new File(imageCachePath));
		if (bitmapFiles != null) {
			final int TIME_DIFF = 30 * 24 * 3600;
			long now = new Date().getTime();
			for (File file : bitmapFiles) {
				if (now - file.lastModified() > TIME_DIFF) {
					file.delete();
				}
			}
		}
	}
	
	/**
	 * 加载网络图片
	 * @author William
	 *
	 */
	class LoadHpptBitmapTask extends AsyncTask<String, Void, byte[]> {
		private String url = null;
		private View view = null;
		private boolean isScale = false;
		private boolean isCahce = false;
		
		public LoadHpptBitmapTask(String url, View view, boolean isScale, boolean isCahce) {
			loadCount ++;
			this.url = url;
			this.isScale = isScale;
			this.isCahce = isCahce;
			this.view = view;
		}
		
		
		protected byte[] doInBackground(String... params) {
			byte[] isRet = null;
			try {
				isRet =  HttpManage.httpBitmap(url);
			} catch (Exception e) {
			}
			return isRet;
		}

		
		protected void onPostExecute(byte[] result) {
			super.onPostExecute(result);
			loadCount --;
			if (result != null) {
				Bitmap bitmap = null;
				
//				Bitmap bitmap = BitmapFactory.decodeFile(pathName);
				
				if (DeviceUtil.isSdcardEnable() && isCahce) {
					String suffix = url.substring(url.length() - 4, url.length()).replace("/", "-");
					String pathName = MD5.getMD5(url) + suffix;
					BitmapUtil.saveBitmapByteToSDCard(result, imageCachePath, pathName);
					
					if (isScale) {
						Options opts = new Options();
						opts.inJustDecodeBounds = true;
						BitmapFactory.decodeFile(imageCachePath + pathName, opts);
						opts.inSampleSize = computeInitialSampleSize(opts, -1, 256 * 256);
						opts.inJustDecodeBounds = false;
						bitmap = BitmapFactory.decodeFile(imageCachePath + pathName, opts);
					} else {
						bitmap = decodeBitmap(imageCachePath + pathName);
					}
				} else {
					if (isScale) {
						Options opts = new Options();
						opts.inJustDecodeBounds = true;
						BitmapFactory.decodeByteArray(result, 0, result.length, opts);
						opts.inSampleSize = BitmapManage.computeInitialSampleSize(opts, -1, 128 * 128);
						opts.inJustDecodeBounds = false;
						bitmap =  BitmapFactory.decodeByteArray(result, 0, result.length, opts);
					} else {
						bitmap = decodeBitmap(result);
					}
				}
				
				if (bitmap != null) {
					String key = MD5.getMD5(url) + isScale;
					put(key, bitmap);
					if (view instanceof ImageView)
						((ImageView) view).setImageBitmap(bitmap);
					else
						view.setBackgroundDrawable(new BitmapDrawable(bitmap));
				}
				
//				ViewGroup.LayoutParams params = imageView.getLayoutParams();
//				params.height = result.getHeight() * params.width / result.getHeight() ;
//				imageView.setLayoutParams(params);
				
				loadNext();
			}
		}
	}
	
	private void loadNext() {
		if (willLoadList.size() > 0) {
			WillLoadModel model = willLoadList.get(0);
			new LoadHpptBitmapTask(model.url, model.view, model.isScale, model.isCache).execute("");
			willLoadList.remove(0);
		}
	}
	
	private class WillLoadModel {
		String url = null;
		View view = null;
		boolean isScale = false;
		boolean isCache = false;
		
		public WillLoadModel(String url, View view, boolean isScale, boolean isCache) {
			this.url = url;
			this.view = view;
			this.isScale = isScale;
			this.isCache = isCache;
		}
	}
	
	private Bitmap decodeBitmap(String absolutePath) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		//这个isjustdecodebounds很重要
		opt.inJustDecodeBounds = true;
		Bitmap bm = null;
		bm = BitmapFactory.decodeFile(absolutePath, opt);
		//获取到这个图片的原始宽度和高度
		int picWidth = opt.outWidth;
		int picHeight = opt.outHeight;
		//获取屏的宽度和高度
		Display display = DeviceUtil.getScreenPixels((Activity)context);
		int screenWidth = display.getWidth();
		int screenHeight = display.getHeight();
		//isSampleSize是表示对图片的缩放程度,比如值为2图片的宽度和高度都变为以前的1/2
		opt.inSampleSize = 1;
		//根据屏的大小和图片大小计算出缩放比例
		if(picWidth > picHeight){
			if(picWidth > screenWidth)
				opt.inSampleSize = picWidth/screenWidth;
		}
		else{
			if(picHeight > screenHeight)
				opt.inSampleSize = picHeight/screenHeight;
		}
		//这次再真正地生成一个有像素的,经过缩放了的bitmap
		opt.inJustDecodeBounds = false;
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		bm = BitmapFactory.decodeFile(absolutePath, opt);
		return bm;
	}
	
	private Bitmap decodeBitmap(byte[] bitmapBtye) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		//这个isjustdecodebounds很重要
		opt.inJustDecodeBounds = true;
		Bitmap bm = null;
		bm = BitmapFactory.decodeByteArray(bitmapBtye, 0, bitmapBtye.length);
		//获取到这个图片的原始宽度和高度
		int picWidth = opt.outWidth;
		int picHeight = opt.outHeight;
		//获取屏的宽度和高度
		Display display = DeviceUtil.getScreenPixels((Activity)context);
		int screenWidth = display.getWidth();
		int screenHeight = display.getHeight();
		//isSampleSize是表示对图片的缩放程度,比如值为2图片的宽度和高度都变为以前的1/2
		opt.inSampleSize = 1;
		//根据屏的大小和图片大小计算出缩放比例
		if(picWidth > picHeight){
			if(picWidth > screenWidth)
				opt.inSampleSize = picWidth/screenWidth;
		}
		else{
			if(picHeight > screenHeight)
				opt.inSampleSize = picHeight/screenHeight;
		}
		//这次再真正地生成一个有像素的,经过缩放了的bitmap
		opt.inJustDecodeBounds = false;
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		bm = BitmapFactory.decodeByteArray(bitmapBtye, 0, bitmapBtye.length);
		return bm;
	}
	
	public static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
	    double w = options.outWidth;
	    double h = options.outHeight;

	    int lowerBound = (maxNumOfPixels == -1) ? 1 :
	            (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));

	    int upperBound = (minSideLength == -1) ? 128 :
	            (int) Math.min(Math.floor(w / minSideLength),
	            Math.floor(h / minSideLength));
	 

	    if (upperBound < lowerBound) {
	        // return the larger one when there is no overlapping zone.
	        return lowerBound;

	    }
	 

	    if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
	        return 1;
	    } else if (minSideLength == -1) {
	        return lowerBound;
	    } else {
	        return upperBound;
	    }
	}  
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值