1

I want to create icons similary to the google contact app.
I wish to provide a background color and a text and generate the icon.

enter image description here

What I'm trying at the moment is something like the solution here.
I'm using the CircularImageView external library and it seems to be the problem. In fact if I try to do:

CircularImageView imageView;
....
Drawable d = new TextDrawable("My Text", mycolor, textSize);
imageView.setImageDrawable(d);

I get this error:

java.lang.IllegalArgumentException: width and height must be > 0
at android.graphics.Bitmap.createBitmap(Bitmap.java:829)
at android.graphics.Bitmap.createBitmap(Bitmap.java:808)
at android.graphics.Bitmap.createBitmap(Bitmap.java:775)
at com.pkmmte.view.CircularImageView.drawableToBitmap(CircularImageView.java:327)

while if I use the standard ImageView it works. Any advice?

Community
  • 1
  • 1
laks.it
  • 165
  • 14
  • TextDrawable? Is this a library if so which one? – timr Jan 06 '16 at 21:39
  • Please mark which line of code throws the exception and maybe add some more... That's too little information – David Medenjak Jan 06 '16 at 21:41
  • No it's the name used in the answer I mentioned [here you can see](http://stackoverflow.com/questions/34643277/android-imageview-setimagedrawable-with-programmatically-created-drawable) – laks.it Jan 06 '16 at 21:42

2 Answers2

2

I've already found on GitHub a library, which makes your desired effect:

TextDrawable

This light-weight library provides images with letter/text like the Gmail app. It extends the Drawable class thus can be used with existing/custom/network ImageView classes. Also included is a fluent interface for creating drawables and a customizable ColorGenerator.

https://github.com/amulyakhare/TextDrawable

As you wish to create your own implementation, try to read carefully code of this library and step-after-step implement your own version

Hope it help

piotrek1543
  • 19,130
  • 7
  • 81
  • 94
  • if you feel it's good answer for your question please mark this post. It would help people with similar problem ;-) – piotrek1543 Jan 06 '16 at 22:04
0

The problem you see is because the library you are using does not account for drawables without fixed dimensions.

You can see here that it uses the drawable intrinsic height and width, which both default to -1 to suggest that the drawable will just fill any sized bitmap.

To fix your problem you would just need to override getIntrinsicHeight() in TextDrawable to return values > 0.

@Override
public int getIntrinsicHeight() {
    return 88;
}

@Override
public int getIntrinsicWidth() {
    return 88;
}

This would suggest your drawable to be a size of 88x88px. To further improve this you would need to supply dp -> px values, so that your drawables don't get stretched on higher resolution devices or squeezed on low dpi ones.

David Medenjak
  • 33,993
  • 14
  • 106
  • 134