This method places a centered text on top of a bitmap object. You can modify the method to add parameters like a custom color, alignment or others.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public static Bitmap writeTextOnDrawable(Context context, Bitmap bitmap, String text, int textSize) { Bitmap bm = Bitmap.createBitmap(bitmap); Typeface tf = Typeface.DEFAULT_BOLD; Paint paint = new Paint(); paint.setStyle(Style.FILL); paint.setColor(Color.WHITE); paint.setTypeface(tf); paint.setTextAlign(Align.CENTER); paint.setAntiAlias(true); paint.setTextSize(16); Rect textRect = new Rect(); paint.getTextBounds(text, 0, text.length(), textRect); Canvas canvas = new Canvas(bm); int xPos = (canvas.getWidth() / 2) - 2; //-2 is for regulating the x position offset int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2)) ; canvas.drawText(text, xPos, yPos, paint); return new BitmapDrawable(context.getResources(), bm).getBitmap(); } |