在固定长宽imageView上,显示图片指定区域
最近做脸搜项目,在固定imageView长宽的列表要,无论原图是什么大小和形状,要使图片充满屏幕。有人会说那用
ScaleType.CENTER_CROP不就好了吗。对!但是有个问题会居中显示。现在的需求是,要显示带脸部的区域。
上效果图(这里以一张大图为原图):
相信你们看到了。这张大图,如果用ScaleType.CENTER_CROP,那么只会显示,女孩的肚子。这样在项目列表页极其影响美观。
在得到需求后,在网上找了大部分资料。但最佳的都是要根据bitmap截图,产生新的bitmap.我这里是列表页,那么大大加大我们的内存压力。
经过大量的思索,怒自定义view;
思路:不截取bitmap,只在imageView上通过滑动来实现。
有了这条线那就好办了:
1,有2层view
2、里面一层就是我们要展示的imageView
3、外面一层是真正给用户看到的一层FrameLayout
4、通过LayoutParams来对imageView进行滑动
源码里都有详细注释。因为时间问题。写博客上传代码,也是自己写笔记。还得继续赶项目。
一同学习,一起分享。大神勿喷,支持原创
关键代码:
this.pic_with = pic_with; this.pic_height = pic_height; int expla_width = UIUtil.getWidth(mContext); int sourceScale_height = expla_width * pic_height / pic_with;//按图片比例放大的实际高度 Log.e("实际高度是多少咯", sourceScale_height + ""); int view_height = expla_width * 9 / 16;//控件的高度 int face_up_left_y = expla_width / pic_with * Up_left_y; int face_down_right_y = expla_width / pic_with * Down_right_y; //可移动的y轴区域 int can_move_y = sourceScale_height - view_height; //脸部中心点在 int point_y = face_up_left_y + (face_down_right_y - face_up_left_y) / 2; //将图片宽度放大到控件宽度,如果放大后的图片高度大于控件高度即可 //否则将图片高度放大到控件高度。就是用最大的缩放比 if (sourceScale_height > view_height) { imgBg.setScaleType(ImageView.ScaleType.FIT_XY); FrameLayout.LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams.width = expla_width; layoutParams.height = expla_width * pic_height / pic_with; layoutParams.topMargin = 0; if (point_y >= 0 && point_y <= view_height / 2) { //说明脸部中心位置在控件上半部分,那么不做处理 } else if (point_y > view_height / 2) { //只要图片区域在下半部分那么走 //即将要移动的图片高度 int will_move_y = point_y - (view_height / 2); if (will_move_y <= can_move_y) {//如果要移动的区域 小于可移动的区域 layoutParams.topMargin = -will_move_y; } else { layoutParams.topMargin = -can_move_y; } } imgBg.setLayoutParams(layoutParams); Glide.with(mContext) .load(imgUrl) .asBitmap() .dontAnimate() .into(imgBg); } else { FrameLayout.LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams.width = view_height * pic_with / pic_height; layoutParams.height = view_height; layoutParams.topMargin = 0; imgBg.setLayoutParams(layoutParams); imgBg.setScaleType(ImageView.ScaleType.FIT_XY); Glide.with(mContext) .load(imgUrl) .asBitmap() .dontAnimate() .into(imgBg); }