0

I have a bitmap and I am trying to draw a text over the bitmap at the top right corner. But at the first place I am not able to draw any text over it. I am converting a layout to bitmap and then trying to draw text over it. But its not working out. Here is my code:

private Bitmap viewToBitmap(LinearLayout layout) {
        Bitmap bitmap = Bitmap.createBitmap(layout.getWidth(), layout.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        layout.draw(canvas);
        canvas=new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setAntiAlias(true);
        paint.setTextSize(14.f);
        paint.setTextAlign(Paint.Align.CENTER);
        canvas.drawText("Hello Android!", 0, 0, paint);
        return bitmap;
    }
sagar suri
  • 4,351
  • 12
  • 59
  • 122

1 Answers1

3

Please pay much attention to the text position & alignment.

private Bitmap viewToBitmap(View view)
{
    Bitmap result = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(result);
    view.draw(canvas);

    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    paint.setAntiAlias(true);
    paint.setTextSize(14);
    paint.setTextAlign(Paint.Align.RIGHT);
    canvas.drawText("Hello Android!", view.getWidth(), 14, paint); // draw watermark at top right corner
    return result;
}
Run
  • 2,148
  • 2
  • 12
  • 29