Handling large images in Android apps has always been a little tricky. With Facebook Fresco, however, you can add huge images to your app, including animated GIFs and WebP files, without having to worry about memory and size issues. In this tutorial, I’m going to help you get started with it.
To follow along, you’ll need the following:
To be able to use Fresco in your project, you must add it as a
compile dependency in the app module’s build.gradle file.
By default, Fresco doesn’t support animated GIFs or WebP files. If you want to handle those formats, you must add the following
Fresco needs one more configuration step. It must be initialized as soon as your app starts. More precisely, you must initialize Fresco inside the
onCreate() method of the
Here’s how you would do it:
You must, of course, also add a
name attribute to the
<application> tag in your manifest file to mention this new class.
<application android:name=".FrescoApp" ....
Oh, and while you are there, request for the
INTERNET permission as well, because we’ll be loading images from the Internet.
Let us now add a
SimpleDraweeView widget to our layout. This is the widget inside which we will be displaying the image. It can handle images of several different formats.
Note how I have specified actual numbers instead of
wrap_content for the width and height of the widget. This is important for Fresco to work correctly.
Now that we have our widget, let’s write some Java code to display a JPEG image inside it. Well, it takes just two lines of code.
First, initialize the widget using
Next, call its
setImageURI() method and pass a URL to it, which points to your large JPEG file. If you don’t know where to find such images, the space subreddit is a good place to start.
And that’s it. If you run the app now, you should be able to see the large image.
Displaying an animated GIF takes a little more work. If you try using the
setImageURI() method to display an animated GIF, you would end up seeing its first frame only.
To display GIFs, you must create a
DraweeController object first and use it to load the GIF.
First create a builder for the
DraweeController using the
Fresco.newDraweeControllerBuilder() method. Next, call its
setUri() method to specify the URL you want to load. The reactiongifs subreddit is a good place to find animated GIFs.
You must also remember to pass
true to its
setAutoPlayAnimations() method, to make sure that the GIF starts playing as soon as it is loaded. Finally, call the
build() method to generate the
Once generated, you can assign the
DraweeController object to the
Run the app again to see your animated GIF playing.
Displaying an animated WebP file is just as easy. All you need to do is point the
DraweeController to its URL.
In this tutorial, you learned how to use Facebook Fresco to manage large image files. I’ll be writing more tutorials about this library because it has a lot more to offer. Stay tuned!