Draw multi-line text to Canvas
I found another way using static layouts. The code is here for anyone to refer to:
TextPaint mTextPaint=new TextPaint();
StaticLayout mTextLayout = new StaticLayout(mText, mTextPaint, canvas.getWidth(), Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
canvas.save();
// calculate x and y position where your text will be placed
textX = ...
textY = ...
canvas.translate(textX, textY);
mTextLayout.draw(canvas);
canvas.restore();
Just iterate through each line:
int x = 100, y = 100;
for (String line: text.split("\n")) {
canvas.drawText(line, x, y, mTextPaint);
y += mTextPaint.descent() - mTextPaint.ascent();
}
Unfortunately Android doesn't know what \n
is. What you have to do is strip the \n
and then offset the Y to get your text on the next line. So something like this:
canvas.drawText("This is", 100, 100, mTextPaint);
canvas.drawText("multi-line", 100, 150, mTextPaint);
canvas.drawText("text", 100, 200, mTextPaint);
I have written complete example
colors.xml
<color name="transparentBlack">#64000000</color>
java class
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.amit);
ImageView imageView = (ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(drawTextToBitmap(this, bm, "Name: Kolala\nDate: Dec 23 2016 12:47 PM, \nLocation: 440 Banquets & Restaurents"));
}
public Bitmap drawTextToBitmap(Context gContext,
Bitmap bitmap,
String gText) {
Resources resources = gContext.getResources();
float scale = resources.getDisplayMetrics().density;
android.graphics.Bitmap.Config bitmapConfig =
bitmap.getConfig();
// set default bitmap config if none
if(bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
// resource bitmaps are imutable,
// so we need to convert it to mutable one
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
// new antialised Paint
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
// text color - #3D3D3D
paint.setColor(Color.WHITE);
// text size in pixels
paint.setTextSize((int) (25 * scale));
// text shadow
paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
// draw text to the Canvas center
Rect bounds = new Rect();
int noOfLines = 0;
for (String line: gText.split("\n")) {
noOfLines++;
}
paint.getTextBounds(gText, 0, gText.length(), bounds);
int x = 20;
int y = (bitmap.getHeight() - bounds.height()*noOfLines);
Paint mPaint = new Paint();
mPaint.setColor(getResources().getColor(R.color.transparentBlack));
int left = 0;
int top = (bitmap.getHeight() - bounds.height()*(noOfLines+1));
int right = bitmap.getWidth();
int bottom = bitmap.getHeight();
canvas.drawRect(left, top, right, bottom, mPaint);
for (String line: gText.split("\n")) {
canvas.drawText(line, x, y, paint);
y += paint.descent() - paint.ascent();
}
return bitmap;
}
}