Fresco 网络获取图片,自动适配宽高

原因:

Fresco 的图片控件 SimpleDraweeView,宽高不能都是Wrap_Content。
Fresco 有做说明:链接

问题:

如果图片是从网络获取,或预先不知道其宽高的情况下
无法给图片控件设置一个固定的宽高或者比例

解决办法:

1.宽高可以设置wrap_content
2.在代码中给SimpleDraweeView设置监听
3.获取到图片后,触发加载完成的回调方法(onFinalImageSet),从图片信息对象(ImageInfo)中知道其宽高,再重新设置SimpleDraweeView的真实宽高。

具体代码:

activity_fresco.xml:


Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fresco);

    final SimpleDraweeView mSdvImg = (SimpleDraweeView)findViewById(R.id.sdv);

    DraweeController controller = Fresco.newDraweeControllerBuilder()
        .setOldController(mSdvImg.getController())
        .setControllerListener(new ControllerListener() {
            @Override
            public void onSubmit(String id, Object callerContext) {

            }

            @Override
            public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
                adjustSdv(mSdvImg,imageInfo.getWidth(),imageInfo.getHeight());
            }

            @Override
            public void onIntermediateImageSet(String id, ImageInfo imageInfo) {

            }

            @Override
            public void onIntermediateImageFailed(String id, Throwable throwable) {

            }

            @Override
            public void onFailure(String id, Throwable throwable) {

            }

            @Override
            public void onRelease(String id) {

            }
        })
        .setUri(Uri.parse(model.getPicUrl()))
        .build();
    mSdvImg.setController(controller);

} 

private void adjustSdv(SimpleDraweeView image,int width,int height){
    LinearLayout.LayoutParams params = (LayoutParams) image.getLayoutParams();
    params.width = screenWidth;
    params.height = (int) ((float)height/width * screenWidth);
    image.setLayoutParams(params);
}

你可能感兴趣的:(Fresco 网络获取图片,自动适配宽高)