6

I've an Android ListView containing some emails. Some of them have contact thumbnails while some of them don't. For unknown contact thumbnails, I want to create a Bitmap, containing the initials of the corresponding email id. How can I achieve that? I've seen some Android apps using this technique to display contact thumbnail like this:

enter image description here

To start with, I'm using the following code:

ImageView iv=(ImageView)findViewById(R.id.imageView1);
    TextView view = (TextView)findViewById(R.id.textView1);

    Bitmap b=Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    view.draw(c);
    iv.setImageBitmap(b);

Where the TextView holds a simple string. Unfortunately, it doesn't work. Can anyone please give me some pointers? Thanks a lot for your help!

Vinit Shandilya
  • 1,643
  • 5
  • 24
  • 44

3 Answers3

11

Well you're on the right track. Try it something like this.

ImageView iv=(ImageView)findViewById(R.id.imageView1);

Bitmap b=Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
c.drawText(initials,x,y,paint);
iv.setImageBitmap(b);

You should create your own logic to center the text. You could use some of the following helper method Paint.getTextSize() to find out how much space the text needs.

Gent Ahmeti
  • 1,559
  • 13
  • 17
1

Simple using this library, you can try it :D

https://github.com/fahmisdk6/AvatarView

this code in your XML File

<me.fahmisdk6.avatarview.AvatarView
            android:id="@+id/avatar_user5"
            android:layout_width="48dp"
            android:layout_height="48dp"
            app:avCornerRadius="8dp"
            app:avBgTextColor="@color/colorAccent"
            app:avTextColor="@color/colorPrimary"
            app:avTextSize="10sp"
            app:avFont="font/avenir_black.ttf"/>

And this in Java File

AvatarView avatarView5 = (AvatarView) findViewById(R.id.avatar_user5);
avatarView5.bind("Fahmi Sidik", "https://avatars2.githubusercontent.com/u/10940190?v=3&s=460");
Deni Rohimat
  • 162
  • 7
0

Read this answer.He has used excellent strategy of using button instead of creating bitmap. Coupled with this you can try to select from a set of colors(for background and text), try to use material design guidelines.This answer has explained how to do so.