您的位置:首页 > 其它

完美解决glide+StaggeredGridLayoutManager 图片加载大小不正常的问题

2017-04-27 18:29 1466 查看
先说下我的目标,公司要求每张图片宽度是充满item的,高度是根据图片高度缩放的,所以要求用瀑布流实现,但是我当我用SwipeToLoadLayout 做下拉刷新的时候,发现每次加载图片,大小都有可能不一样,但是 首次加载的时候.图片显示是正常的,我猜测,这个跟glide的图片缓存有关系,但是当我设置 glie的skipMemoryCache(true),不让他缓存还有DiskCacheStrategy.RESULT    dontransform 各种属性全试了一遍,发现还是没达到效果.那么可以排除glide的锅,应该是recyclerview的图片缓存除了问题,如果有兴趣的同学可以去研究下recyclerview的缓存机制下面我说下我研究一天的解决方案:思路就是在第一次用glide 拿到图片之后,就取bitmap的宽高,然后  按照宽高比获取图片高度,因为图片宽度是定死的我这个2列的瀑布流, 宽度就取屏幕一半.  然后  这个宽高 同时去改变  imageview的宽高和bitmap的宽高.这样就能保证图片不变形,而且,每次下拉刷新的时候都不会改变其大小.下面是我的关键代码,如果有疑问可以加我qq:385813241,虽然挺简单,但是我相信有人需要先说下图片设置的属性
<ImageView
android:id="@+id/work_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="@drawable/ic_launcher" />
fitCenter 表示充满view的宽度,高度按照原图比例显示在Recyclerview的adapter里面
public void onBindViewHolder(final MyHolder holder, final int position) {

//为了方便阅读,我在这边定义个变量
ImageView imageView;//你要加载图片的容器
Glide.with(act)
.load("图片url")
.asBitmap()
.into(new SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {

@Override
public void onResourceReady(Bitmap bitmap, GlideAnimation glideAnimation) {

//这个bitmap就是你图片url加载得到的结果
//获取bitmap信息,可赋值给外部变量操作,也可在此时行操作。
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) imageView.getLayoutParams();//获取你要填充图片的布局的layoutParam
layoutParams.height = (int) (((float) bitmap.getHeight()) / bitmap.getWidth() * ScreenUtils.getScreenWidth(act) / 2 );
//因为是2列,所以宽度是屏幕的一半,高度是根据bitmap的高/宽*屏幕宽的一半
layoutParams.width =  ScreenUtils.getScreenWidth(act) / 2;//这个是布局的宽度
imageView.setLayoutParams(layoutParams);//容器的宽高设置好了
bitmap = zoomImg(bitmap, layoutParams.width, layoutParams.height);
// 然后在改变一下bitmap的宽高
holder.workImage.setImageBitmap(bitmap);
}

});

}
}
//改变bitmap尺寸的方法
public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {// 获得图片的宽高int width = bm.getWidth();int height = bm.getHeight();// 计算缩放比例float scaleWidth = ((float) newWidth) / width;float scaleHeight = ((float) newHeight) / height;// 取得想要缩放的matrix参数Matrix matrix = new Matrix();matrix.postScale(scaleWidth, scaleHeight);// 得到新的图片Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);return newbm;}
//获取屏幕宽度的方法
public static int getScreenWidth(Context context){WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);DisplayMetrics outMetrics = new DisplayMetrics();wm.getDefaultDisplay().getMetrics(outMetrics);return outMetrics.widthPixels;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: