Slavik Y
Slavik Y

Reputation: 125

Simplest way to put text on drawable programmatically

I have this icon: icon

I am going to work with it as drawable.

Drawable myIcon = getResources().getDrawable( R.drawable.icon );

I need programmaticaly put some text on it (file extension).

This is my desired result: desired result.

I can't make several static icons because I can receive arbitrary file extension

Upvotes: 6

Views: 8509

Answers (3)

Pier Giorgio Misley
Pier Giorgio Misley

Reputation: 5351

If you are not going to print somewhere this image and you simply have to display it on the screen, probably the easiest way is to print the text on the center of the img.

You can do it by using a RelativeLayout

<RelativeLayout> // Only works inside a RelativeLayout
  <ImageView
    android:id="@+id/myImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/myImageSouce" />

  <TextView
    android:id="@+id/myImageText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/myImage"
    android:layout_alignTop="@+id/myImage"
    android:layout_alignRight="@+id/myImage"
    android:layout_alignBottom="@+id/myImage"
    android:layout_margin="1dp"
    android:gravity="center"
    android:text="Hello"
    android:textColor="#000000" />
 </RelativeLayout>

This is probably the easiest solution and it will align the text at the center of the image, based on img sizes.

Upvotes: 0

Rishabh Mahatha
Rishabh Mahatha

Reputation: 1271

public BitmapDrawable writeOnDrawable(int drawableId, String text){

        Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId).copy(Bitmap.Config.ARGB_8888, true);

        Paint paint = new Paint(); 
        paint.setStyle(Style.FILL);  
        paint.setColor(Color.BLACK); 
        paint.setTextSize(20); 

        Canvas canvas = new Canvas(bm);
        canvas.drawText(text, 0, bm.getHeight()/2, paint);

        return new BitmapDrawable(bm);
    }

Use this method.will help you.

Upvotes: 18

Ankur Khandelwal
Ankur Khandelwal

Reputation: 1070

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">


                <ImageView
                    android:id="@+id/folder"
                    android:src="@drawable/image_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />


                 <TextView

                    android:textColor="@color/green"
                    android:textStyle="bold"
                    android:id="@+id/text"
                    android:text="10"
                    android:layout_centerInParent="true"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </RelativeLayout>

Upvotes: 2

Related Questions