Search code examples
androidimagefrescoandroid-wrap-content

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


Solution

  • Since you already know the exact dimensions of the image, you can simply calculate the aspect ratio of your image and then just set the aspect ratio in XML or Java. This works out-of-the-box and you don't need any custom views or DP / pixel calculations as suggested in other answers.

    For your example, this would be w/h = 730/760 = 0.96052631578

    Now you can just set it: In XML:

    <com.facebook.drawee.view.SimpleDraweeView
        android:id="@+id/my_image_view"
        android:layout_width="match_parent" <!-- or the desired width -->
        android:layout_height="wrap_content"
        fresco:viewAspectRatio="0.96052631578" <!-- your aspect ratio -->
        <!-- other attributes -->
    

    Or in Java:

    mSimpleDraweeView.setAspectRatio(0.96052631578f); // or whatever your aspect ratio is
    

    See also http://frescolib.org/docs/using-drawees-xml.html at the very bottom.