How can i use Glide library to load Bitmap into my ImageView? I want to create a custom image with text and load it into imageview using Glide.
This is my method to create custom bitmap with text
public Bitmap imageWithText(String text) {
TextView tv = new TextView(context);
tv.setText(text);
tv.setTextColor(Color.WHITE);
tv.setBackgroundColor(Color.BLACK);
tv.setTypeface(null, Typeface.BOLD);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(20);
tv.setPadding(0, 25, 0, 0);
Bitmap testB = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(testB);
tv.layout(0, 0, 100, 100);
tv.draw(c);
return testB;
}
But when i try to load this bitmap using glide i'm getting error
Glide.with(getContext()).load(imageWithText("Random text")).into(holder.imgPhoto);
According to the documentation, I don't think the load() method can take a Bitmap as parameter. The image source (i.e., the parameter) could be a URL, drawable resource, and file.
However, if you want to load a Bitmap into an ImageView, you don't need to use the Glide library. Just use the below statement
I don't know performance, but you can try this:
First of all transform your bitmap as byte[] array:
Then use glide in this way:
In your case:
@rookiedev is right, there's no
load(Bitmap)
in Glide, for a reason: acquiring aBitmap
usually takes time and sometimes blocking I/O. So it's not good practice to callimageWithText
on the UI thread. Update: That being said I proposed this feature a while back; and while the hacks are easier to do you can find the "Glide way" below, which I highly recommend.Glide is designed to be flexible and this problem demonstrates that trait extremely well. The following implementation may seem long, but all pieces have their reason for existence. Given the performance gain, this amount of code to fit your generator into Glide's world is not much. I tried to format it to be short, collapsing irrelevant parts and using static imports to be shorter (see the end for imports).
The code also includes programmatically generated UI so you can just copy-paste all the below code into
GlideGeneratedImageListFragment.java
and run it; the only external dependency is support lib'sRecyclerView
.Here's how it looks like (real scrolling is much smoother, GIF is really low FPS):
Notice how it loads the first few items and then gradually loads the rest. It takes a little that the memory cache and pool warms up, but you can use a preloader if you want even smoother display. After it's warmed up it scrolls nicely. The delete button on the action bar calls
Glide.clearDiskCache()
andGlide.clearMemory()
so it starts regenating the items again.You can try, The code below adds an ImageView and a TextView to FrameLayout :
The result will be as shown below :