简单布局-图文加载textview

网上发现有大神写的一些好东西,我自己也收藏下,

【链接】LiushuiXiaoxia/TextStylePlus

https://github.com/LiushuiXiaoxia/TextStylePlus

这个图文加载textview 比我自己整的好很多,就是不适合大图以及不规则顺序的加载,适合图标+文字布局,合并一个控件显示

如果从网上获取数据,数据包含图文结合,那么这个方法用不了,就用自己写的

String html = t.getComment();
			if (html.contains(".jpg") || html.contains(".png")
					|| html.contains("jpeg") || html.contains(".gif")) {

				if (html.contains("http://") || html.contains("https://")) {
					String regexstr = "<(?!img).*?>"; //
					// 去除所有标签,只剩img
					html = html.replaceAll(regexstr, "");
				}
			} else {
				html = html.replaceAll("\r", "");
				html = html.replaceAll("\n", "");
				html = html.replaceAll("\t", "");
				html = html.replaceAll("</?[p|P][^>]*>", "");
			}
			if(t.getIsreply().equals("1")){
				String str ="<font color=\"#298fb7\">" + t.getReauthor() + "</font>回复"+"<font color=\"#298fb7\">" + t.getAuthor() + "</font>:";
				html =str+html;
			}else{
				String str ="<font color=\"#298fb7\">" + t.getAuthor() + "</font>:";
				html =str+html;
			}
			Spanned spanned = Html.fromHtml(html, new MyImageGetter(mContext,
					replytv, memoryCache, null, null), null);
public class MyImageGetter implements ImageGetter {

	private Context context;
	private TextView tv;

	private MemoryCache memoryCache ;
	private Map<String, Bitmap> bitmapList;
	private ArrayList<String> imageStrs ;
	private Drawable drawable = null;
	private int simplesize = 1;	//图片压缩的倍数
	private int imageWid = 480;	//图片有服务器压缩为480宽度
	//	private int imgdelarea = 60;	//图片减去的显示区域
//	private int byimgarea = 30; 	//old版本的
	private int imgdelarea = 40;	//图片减去的显示区域
	private int byimgarea = 20; 	//
	private Bitmap bmp=null ;
	public MyImageGetter(Context context, TextView tv, MemoryCache memoryCache,
						 Map<String, Bitmap> bitmapList, ArrayList<String> imageStrs) {
		this.context = context;
		this.tv = tv;
		this.memoryCache = memoryCache;
		this.bitmapList = bitmapList;
		this.imageStrs = imageStrs;

		imgdelarea = deletewidthpx();
	}

	@Override
	public Drawable getDrawable(String source) {
		// 先判断回复的图片是否是本地的表情
		int smilyId = Common.getSmilyStr(source);
		if (smilyId != 0) { // 是本地的表情
			WindowManager wm = (WindowManager) context  //context
					.getSystemService(Context.WINDOW_SERVICE);

			int width = wm.getDefaultDisplay().getWidth();
			drawable = context.getResources().getDrawable(smilyId);
			// drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
			// drawable.getIntrinsicHeight());
			drawable.setBounds(0, 0, width / 20, width / 20);
			return drawable;
		} else {
			Resources res = context.getResources();
			String height = ForumPostActivity.imageHeight.get(source);
			String width = ForumPostActivity.imageHeight.get(source+"_w");
			URLDrawable drawable ;
			if(height!=null && !height.equals("") && !height.equals("0")) {
				drawable = new URLDrawable(null, height, width);
//						res.getDrawable(R.drawable.post_bgimg), height, width);


				DisplayMetrics metrics = new DisplayMetrics();
				((Activity) context).getWindowManager().getDefaultDisplay()
						.getMetrics(metrics);
				// 取drawable的原始尺寸
				int wid = 0;
				if(width!=null && !width.equals(""))
					if (width.contains(".")) {
						int index =width.indexOf(".");
						width =width.substring(0, index);
					}
				wid = Integer.parseInt(width);
				if (height.contains(".")) {
					int index =height.indexOf(".");
					height =height.substring(0, index);
				}
				int hid = Integer.parseInt(height);
				int img_area = metrics.widthPixels - imgdelarea;// 图片显示区域尺寸
				if (wid > img_area) {// 图片原宽度超出图片显示区域,则进行缩放,不超过则显示原始尺寸
					wid = img_area;// 设置图片显示大小和图片显示区域一致
				}
				if(wid > 300) {
					int imgarea_height = (img_area * hid / wid);
					drawable.setBounds(0, 0, img_area, imgarea_height);
				} else {
					drawable.setBounds(0, 0, wid, hid);
				}

			} else {
				drawable = new URLDrawable(
						res.getDrawable(R.drawable.post_default_img3), height, width);
			}
			//先从内存缓存中查找
			Bitmap bitmap = null;
			if(bitmapList!=null) {	//回复的图片
				bitmap = bitmapList.get(source);
			} else if(memoryCache!=null){
				bitmap = memoryCache.get(source);
			}
			Drawable drawablenew = null;
			if(bitmap!=null) {
				drawablenew = new BitmapDrawable(bitmap);
				drawablenew.setBounds(0, 0, bitmap.getWidth(),
						bitmap.getHeight());
				if(drawablenew!=null) {
					drawable.setDrawable(drawablenew);
					tv.setText(tv.getText()); // 通过这里的重新设置 TextView 的文字来更新UI
				}
			} else {
				if (null != source && !"".equals(source)) {
					new ImageAsync(drawable).execute(source);
				}
			}
			return drawable;
		}
	}

	//根据手机分辨率来计算图片所占用的区域
	public int deletewidthpx() {
		DisplayMetrics metrics = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);
		int areaPx = metrics.widthPixels / 240;
		return areaPx * byimgarea;
	}

	//对图片的质量进行压缩
	private Bitmap compressImage(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 35, baos);//质量压缩方法
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
		//释放image占用的资源
		if(image!=null && !image.isRecycled()) {
			image.recycle();
			image = null;
		}
		try {
			baos.close();
			isBm.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}


	private class ImageAsync extends AsyncTask<String, Integer, Drawable> {

		private URLDrawable drawable;

		public ImageAsync(URLDrawable drawable) {
			this.drawable = drawable;
		}

		@Override
		protected Drawable doInBackground(String... params) {
			// TODO Auto-generated method stub
			String source = params[0];// 图片URL
			Drawable draw = fetchDrawable(source);
			if(draw==null) {
				draw = fetchDrawable(source);
			}
			return draw;
		}

		@Override
		protected void onPostExecute(Drawable result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result != null) {
				drawable.setDrawable(result);
				tv.setText(tv.getText()); // 通过这里的重新设置 TextView 的文字来更新UI
			}
		}
	}

	//通过urlstring获取图片inputstream
	private InputStream fetchin(String urlString) throws MalformedURLException, IOException {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpGet request = new HttpGet(urlString);
		HttpResponse response = httpClient.execute(request);
		return response.getEntity().getContent();
	}

	// 获取URL的Drawable对象
	public Drawable fetchDrawable(String urlString) {
		// BitmapDrawable bitmap = null;
		Drawable drawable = null;
		Bitmap bitmap = null;
		int width=0,height=0;

		try {
//			BitmapFactory.Options options = new BitmapFactory.Options();
//			options.inJustDecodeBounds = true;
//			BitmapFactory.decodeStream(new URL(urlString).openStream(), null,
//					options); // 避免内存溢出
//
//			width = options.outWidth;
//			height = options.outHeight;
//			options.inJustDecodeBounds = false;
//			int scale = 1;
//			int temp = width > height ? width : height;
//			while (true) {
//				if (temp / 2 < 120)
//					break;
//				temp = temp / 2;
//				scale = 1;
//			}
			BitmapFactory.Options opt = new BitmapFactory.Options();
			opt.inSampleSize = simplesize;
			opt.inPreferredConfig = Bitmap.Config.RGB_565;// 565代表对应三原色占的位数
			opt.inPurgeable = true;// 设置图片可以被回收
			opt.inInputShareable = true;

//			InputStream in = new URL(urlString).openStream(); //mx4通过此方法获取不到图片
			InputStream in = fetchin(urlString);	//mx4通过http协议进行获取图片
			bitmap = BitmapFactory.decodeStream(in, null, opt); // 容易内存溢出
			if (in != null) {
				in.close();
			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OutOfMemoryError e) {// 若内存溢出,则不做处理
			// TODO: handle exception
			clearBitmap();	//释放bitmap占用的资源

			return null;
//			// 再重新获取
		} finally {
			if (null != bitmap) {
				if(bitmapList==null)
					memoryCache.put(urlString, bitmap);
				else if(bitmapList!=null && !bitmapList.containsKey(urlString)) {
					bitmapList.put(urlString, bitmap);
					imageStrs.add(urlString);
				}

				drawable = new BitmapDrawable(bitmap);
				DisplayMetrics metrics = new DisplayMetrics();
				((Activity) context).getWindowManager().getDefaultDisplay()
						.getMetrics(metrics);

				if (width > metrics.widthPixels
						|| height > metrics.heightPixels)
					// 进行等比例缩放程序
					drawable.setBounds(
							0,
							0,
							metrics.widthPixels,
							(metrics.widthPixels * height / width));
				else
					drawable.setBounds(0, 0, width, height);

			}
		}
		return drawable;
	}

	//从第一张开始清理
	public void clearBitmap() {
		if(bitmapList!=null) {
			try {
				for(int i=0;i<10;i++) {
					if(imageStrs.size()>0) {
						String src = imageStrs.get(0);
						Bitmap bitmap = bitmapList.get(src);
						if(bitmap!=null && !bitmap.isRecycled()) {
							bitmap.recycle();
							bitmap = null;
						}
						imageStrs.remove(0);
						bitmapList.remove(src);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	//释放 bitmap
	public void clearBitmapList() {
		if(bitmapList!=null) {
			try {
				Iterator<Entry<String, Bitmap>> iter = bitmapList.entrySet().iterator();
				int cleanCount = 0;
				while(iter.hasNext() && cleanCount++ <= 10) {
					Entry<String, Bitmap> entry = iter.next();
					Bitmap bitmap = entry.getValue();
					if(bitmap!=null && !bitmap.isRecycled()) {
						bitmap.recycle();
						bitmap = null;
					}
					iter.remove();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}


	public class URLDrawable extends BitmapDrawable {

		private Drawable drawable;
		private String height, width;

		public URLDrawable(Drawable defaultDraw, String height, String width) {
			this.height = height;
			this.width = width;
			setDrawable(defaultDraw);
		}

		private void setDrawable(Drawable nDrawable) {
			drawable = nDrawable;
			getDrawable();
		}

		@Override
		public void draw(Canvas canvas) {
			// TODO Auto-generated method stub
			try {
				if(height!=null && !height.equals("") && !height.equals("0")) {
					try {
						bmp = BitmapFactory.decodeResource(
								context.getResources(),
								R.drawable.post_default_img3);
						if (Integer.parseInt(width) >= bmp.getWidth()
								&& Integer.parseInt(height) >= bmp.getHeight()) {
							int draWidth = 0, draHeight = 0;

							DisplayMetrics metrics = new DisplayMetrics();
							((Activity) context).getWindowManager()
									.getDefaultDisplay().getMetrics(metrics);
							// 取drawable的原始尺寸
							int wid = Integer.parseInt(width); // 图片原始宽度
							int hid = Integer.parseInt(height); // 图片原始高度
							int img_area = metrics.widthPixels - imgdelarea;// 图片显示区域尺寸
							if (wid > img_area) {// 图片原宽度超出图片显示区域,则进行缩放,不超过则显示原始尺寸
								wid = img_area;// 设置图片显示大小和图片显示区域一致
							}
							if (wid > 300) {
								draWidth = img_area;
								draHeight = (img_area * hid / wid);
							} else {
								draWidth = wid;
								draHeight = hid;
							}

							Paint mPaint = new Paint();
							mPaint.setColor(context.getResources().getColor(
									color.post_defaultimgbg));
							Rect rtSource = new Rect(0, 0, draWidth, draHeight);
							canvas.drawRect(rtSource, mPaint);

							int startx = (draWidth - bmp.getWidth()) / 2;
							int starty = (draHeight - bmp.getHeight()) / 2;
							canvas.drawBitmap(bmp, startx, starty, null);
						}
						if (bmp != null && !bmp.isRecycled()) {
							bmp.recycle();
							bmp = null;
						}
					} catch(OutOfMemoryError e) {
					}
				}

				drawable.draw(canvas);
			} catch(Exception e) {
//				e.printStackTrace();
//				Resources res = context.getResources();
//				Drawable dradefault = res.getDrawable(R.drawable.post_default_img3);
//
//				DisplayMetrics metrics = new DisplayMetrics();
//				((Activity) context).getWindowManager().getDefaultDisplay()
//						.getMetrics(metrics);
//				int wid, hid, img_area;
//				// 取drawable的原始尺寸
//				wid = (int) (dradefault.getIntrinsicWidth() * metrics.density);// 图片原始宽度
//				hid = (int) (dradefault.getIntrinsicHeight() * metrics.density);// 图片原始高度
//				// 进行等比例缩放程序
//				dradefault.setBounds(0, 0, wid, hid);
//				dradefault.draw(canvas);

			}
		}

		private void getDrawable() {
			if (null != drawable) {
				DisplayMetrics metrics = new DisplayMetrics();
				((Activity) context).getWindowManager().getDefaultDisplay()
						.getMetrics(metrics);
				int wid, hid, img_area;
				// 取drawable的原始尺寸
				wid = (int) (drawable.getIntrinsicWidth() * metrics.density);// 图片原始宽度
				hid = (int) (drawable.getIntrinsicHeight() * metrics.density);// 图片原始高度
				img_area = metrics.widthPixels - imgdelarea;// 图片显示区域尺寸
				if (wid > img_area) {// 图片原宽度超出图片显示区域,则进行缩放,不超过则显示原始尺寸
					wid = img_area;// 设置图片显示大小和图片显示区域一致
				}
				// 进行等比例缩放程序
//				drawable.setBounds(0, 0, wid, hid);
//				setBounds(0, 0, wid, hid);

				if(wid*simplesize > 300) {
					int imgarea_height = (img_area * hid / wid);
					drawable.setBounds(0, 0, img_area, imgarea_height);
					setBounds(0, 0, img_area, imgarea_height);
				} else {
					int bynum = 1;
					if(metrics.widthPixels > imageWid)
						bynum = simplesize;
					drawable.setBounds(0, 0, wid*bynum, hid*bynum);
					setBounds(0, 0, wid*bynum, hid*bynum);
				}

			}
		}
	}

}

猜你喜欢

转载自274137570-qq-com.iteye.com/blog/2389557