本文以图片的宽度,屏幕的宽度,动态计算适配图片的高度,以添加到RecyclerView 中,显示不同高度的Item。其他实现可以以此类推出来:
效果如下:
适用条件:
1. 图片根据手机屏幕宽度,图片自身的比例计算显示的高度,原尺寸显示图片;
2. 因为 fresco 高度不能像ImageVIew一样设置wrap_content;如果设置了wrap_content 代码中手动设置比例才行;
3. 服务器没有返回图片的宽高。手动加载图片,并计算高度。
基于以上条件,可以继续阅读:
1.布局:
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/sdv_result_img"
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:layout_height="wrap_content"
fresco:actualImageScaleType="fitCenter"
fresco:fadeDuration="300"
/>
2.使用:
((ImgViewHolder) holder).msdv.setImageURI(mDatas.get(position));
FrescoUtils.setControllerListener(((ImgViewHolder) holder).msdv, mDatas.get(position),
UIUtils.getScreenWidth(mcontext));
3.FrescoUtils
public class FrescoUtils {
public static void setControllerListener(final SimpleDraweeView simpleDraweeView, String imagePath, final int imageWidth) {
final ViewGroup.LayoutParams layoutParams = simpleDraweeView.getLayoutParams();
ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() {
@Override
public void onFinalImageSet(String id, @Nullable ImageInfo imageInfo, @Nullable Animatable anim) {
if (imageInfo == null) {
return;
}
int height = imageInfo.getHeight();
int width = imageInfo.getWidth();
layoutParams.width = imageWidth;
layoutParams.height = (int) ((float) (imageWidth * height) / (float) width);
simpleDraweeView.setLayoutParams(layoutParams);
}
@Override
public void onIntermediateImageSet(String id, @Nullable ImageInfo imageInfo) {
Log.d("TAG", "Intermediate image received");
}
@Override
public void onFailure(String id, Throwable throwable) {
throwable.printStackTrace();
}
};
DraweeController controller = Fresco.newDraweeControllerBuilder().setControllerListener(controllerListener).setUri(Uri.parse(imagePath)).build();
simpleDraweeView.setController(controller);
}
}
4.getScreenWidth
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;
}