dbrettschneider
dbrettschneider

Reputation: 3183

Draw on Drawable

I want to draw a number on an existing drawable. Like the unread count at an email icon. The drawable is the top icon of a button. This is my code:

BitmapDrawable d = (BitmapDrawable) button.getCompoundDrawables()[1];
if(d != null) {
    Bitmap src = d.getBitmap();
    Bitmap b = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
    Canvas c = new Canvas(b);

    Paint p = new Paint();
    p.setAntiAlias(true);
    p.setStrokeWidth(1);
    p.setStyle(Style.FILL_AND_STROKE);
    p.setColor(Color.rgb(254, 0, 1));

    c.drawBitmap(src, 0, 0, p);
    c.drawCircle(b.getWidth()-5, 5, 5, p);
    button.setCompoundDrawables(null, new BitmapDrawable(b), null, null);
}

The resulting drawable is emtpy. Is there something wrong with this code?

Thanks in advance.

Upvotes: 1

Views: 2928

Answers (2)

dbrettschneider
dbrettschneider

Reputation: 3183

The new bitmap has to call setBounds(...)

BitmapDrawable dn = new BitmapDrawable(b);
dn.setBounds(d.getBounds());
button.setCompoundDrawables(null, dn, null, null);

Upvotes: 1

Damian
Damian

Reputation: 8072

I'm not sure about your implementation but another way to go about this is to add your bitmap to a framelayout as an imageview and then add a textview (appropriately styled) with an offset; depending where you want the badge e.g. top right hand corner.

Upvotes: 0

Related Questions