Ankit Srivastava Ankit Srivastava - 11 months ago 48
Android Question

How to combine TextView and an image and return an image?

While searching for results i came across this
How can I convert a View to a Drawable?
The idea behind this is I can convert TextView into a bitmap first and then combine the two bitmaps. But by converting the TextView into Bitmap, it would make it lose it's transparency which I don't want.

My idea is to create images like these
enter image description here

Here i want to enclose the text with a drawable shape for that white border.
And then place this textview on an image and then save everything as a bitmap.
Please help

Answer Source

You can try to draw text and lines on canvas.
Below is example method which draws text on drawable image and returns Bitmap.
You can set custom font by calling .setTypeface() on Paint object.
Call canvas.drawLine() to draw line. To customize your line you can create new Paint object, set its color and width by .setColor() and .setStrokeWidth() and pass it in drawLine() together with line coordinates.

public Bitmap drawTextOnBitmap(Context context, int resId, String text) {

        // prepare canvas
        Resources resources = context.getResources();
        float scale = resources.getDisplayMetrics().density;
        Bitmap bitmap = BitmapFactory.decodeResource(resources, resId); bitmapConfig = bitmap.getConfig();
        // set default bitmap config if none
        if (bitmapConfig == null) {
            bitmapConfig =;
        // resource bitmaps are immutable, so we need to convert it to mutable one
        bitmap = bitmap.copy(bitmapConfig, true);
        Canvas canvas = new Canvas(bitmap);

        // new antialiased Paint
        TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        // text color - #3D3D3D
        paint.setColor(Color.rgb(61, 61, 61));
        // text size in pixels
        paint.setTextSize((int) (bitmap.getHeight() / 10 * scale));
        // text shadow
        paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);

        // set text width to canvas width minus 16dp padding
        int textWidth = canvas.getWidth() - (int) (16 * scale);

        // init StaticLayout for text
        StaticLayout textLayout = new StaticLayout(text, paint, textWidth,
                Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);

        // get height of multiline text
        int textHeight = textLayout.getHeight();

        // get position of text's top left corner
        float x = (bitmap.getWidth() - textWidth) / 2;
        float y = (bitmap.getHeight() - textHeight) / 2;

        // draw text to the Canvas center;
        canvas.translate(x, y);

        return bitmap;