Itiel Maimon Itiel Maimon - 4 months ago 27
Android Question

How to set dimensions of a DraweeView to "wrap_content" in the Fresco library

I'm using the

Fresco
library in my app to load images.
The problem is that I can't set my images height to
"wrap_content"
because
"wrap_content"
is not supported in the
Fresco
library.
So how can I make my images to look good using a
DraweeView
?
I looked here but I couldn't find a solution to this problem : frescolib/wrap_content

For example:

<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/intro_image1"
android:layout_width="match_parent"
android:layout_height= // Can't use "wrap_content"
fresco:placeholderImage="@drawable/placeholder_image" />


BTW the images dimensions are 730*760

Answer

You can create Custom view extends SimpleDraweeView like below way

public class WrapContentDraweeView extends SimpleDraweeView {

    // we set a listener and update the view's aspect ratio depending on the loaded image
    private final ControllerListener listener = new BaseControllerListener<ImageInfo>() {
        @Override
        public void onIntermediateImageSet(String id, @Nullable ImageInfo imageInfo) {
            updateViewSize(imageInfo);
        }

        @Override
        public void onFinalImageSet(String id, @Nullable ImageInfo imageInfo, @Nullable Animatable animatable) {
            updateViewSize(imageInfo);
        }
    };

    public WrapContentDraweeView(Context context, GenericDraweeHierarchy hierarchy) {
        super(context, hierarchy);
    }

    public WrapContentDraweeView(Context context) {
        super(context);
    }

    public WrapContentDraweeView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public WrapContentDraweeView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public WrapContentDraweeView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void setImageURI(Uri uri, Object callerContext) {
        DraweeController controller = ((PipelineDraweeControllerBuilder)getControllerBuilder())
                .setControllerListener(listener)
                .setCallerContext(callerContext)
                .setUri(uri)
                .setOldController(getController())
                .build();
        setController(controller);
    }

    void updateViewSize(@Nullable ImageInfo imageInfo) {
        if (imageInfo != null) {
            setAspectRatio((float) imageInfo.getWidth() / imageInfo.getHeight());
        }
    }
}

and then use this way

<com.example.ui.views.WrapContentDraweeView
    android:id="@+id/simple_drawee_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />

Note : make sure you have applied your package name Otherwise it is not work.

Comments