I am developing photography apps in that I overlay an image with text.
Here is my code:
Bitmap mBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.themes11);
// create a mutable bitmap with the same size as the background image's size
bmOverlay = Bitmap.createBitmap(mBitmap.getWidth(),
mBitmap.getHeight(), Bitmap.Config.ARGB_4444);
// create a canvas on which to draw
Canvas canvas = new Canvas(bmOverlay);
TextPaint paint = new TextPaint();
paint.setColor(Color.RED);
paint.setTextSize(40);
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
// if the background image is defined in main.xml, omit this line
canvas.drawBitmap(mBitmap, 0, 0, null);
// draw the text and the point
canvas.drawPoint(50, 100, paint);
// canvas.drawText(InstaTextActivity.CurrentWord, 300, 200, paint);
StaticLayout layout = new StaticLayout(InstaTextActivity.CurrentWord,
paint, display.getHeight(),
android.text.Layout.Alignment.ALIGN_NORMAL, (float) 1.0,
(float) 0.0, true);
canvas.translate(width / 5, height / 5);
layout.draw(canvas);
imageview_img.setImageBitmap(bmOverlay);
In this code I overlay the text on screen width/2 and height/2 it will display on top the image but I want the text to be center-aligned. Also when I write a large text it will align form center to right.
Have a look at the images to see how I want it:
The Image Background:
And the result I want:
Use the below methods to measure the height and width of the text. Then when drawing the text on canvas
left = width/2 - textWidth/2
top = height/2 - textHeight/2
But if you need a multiple line text for long texts, it will be a bit tricky.
This is not a very refined approach(Not optimized for memory usage) but does the job. You will need to modify the code in order to split at the string keeping words intact. Hope this helps.
i using this. working for me.
source : http://www.skoumal.net/en/android-drawing-multiline-text-on-bitmap/
You should use
StaticLayout
for this. It measures and draws multiline text, handling line wrapping, line spacing, alignment etc.The text can even be HTML formatted, just wrap your text in
Html.fromHtml()
: