图片按照指定比例裁剪
需求:按照屏幕比例或者按照指定的宽高比例裁剪,并且保持图片不能缩放。所以想法是按照需求的比例,抠出图片中间那部分。若是加载网络图片,可以用Glide加载过程中的回调。
/** * @param bitmap 源bitmap * @param w 缩放后指定的宽高 * @param h 缩放后指定的高度 * @return 缩放后的中间部分图片 Bitmap */ public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) { Bitmap newbmp = null; int width = bitmap.getWidth(); int height = bitmap.getHeight(); LogUtil.i("zoomBitmap---", "width:" + width + "---" + "height:" + height); if(bitmap!=null){ double whscale=(double)w/(double)h;//宽高比 double hwscale=(double)h/(double)w;//高宽比 int nWidth = (int) (height*whscale); int nHeight = (int) (width*hwscale); try { if (width>height) { if (width<nWidth) { if ((height-nHeight)>nHeight/3) { newbmp = Bitmap.createBitmap(bitmap,0,(int)nHeight/3, width,nHeight); }else{ newbmp = Bitmap.createBitmap(bitmap,0,0, width,nHeight); } }else{ newbmp = Bitmap.createBitmap(bitmap,(int)(width-nWidth)*2/3,0, nWidth,height); } } else if (width<=height) { if (height<nHeight) { if ((width-nWidth)>nWidth/3) { newbmp = Bitmap.createBitmap(bitmap,(int)nWidth/3,0, nWidth,height); }else{ newbmp = Bitmap.createBitmap(bitmap,0,0, nWidth,height); } }else{ newbmp = Bitmap.createBitmap(bitmap,0,(height-nHeight)*2/3, width,nHeight); } } } catch (Exception e) { e.printStackTrace(); return null; } } return newbmp; }
需要注意的是:按比例计算图片宽或高的时候,需要比较比例高与图片本身高的大小。
By LiYing